对象没有'不支持属性或方法parseJSON

Object doesn't support property or method parseJSON

本文关键字:属性 方法 parseJSON 不支持 对象      更新时间:2023-09-26

请在下面找到加载主页时加载的javascript。

    $(document).ready(function() {
       $.post('../business logic/NewsLogic.php', null, function(response) {
             var respObj = $.parseJSON(response);
             if (respObj != null) {
                 alert('I am here ');
             }
});

我无法解析JSON,我得到一个错误,对象不支持属性或方法解析JSON

/*下面是PHP*/的示例

  $newsDAO = new NewsDAO();
  $newsInfo = new News();
  $respArr = array();
  $respArr = $newsDAO->showAllNews();
  print json_encode($respArr);

其中respArr是一个包含元素的数组。

您能发布$.post响应吗?

无论如何,我认为使用$.ajax和json作为dataType会更好,比如:

   $(document).ready(function() {
        $.ajax({
type:'post',
        url: '../business logic/NewsLogic.php',
        data: 'somequerystring',
        dataType: 'json',
        success: function(jsonObject) {
        }
        })
    });

使用JSON.parse方法

在你的代码中,它会像一样适合

var respObj = JSON.parse(response);

*********编辑*********

大多数浏览器都支持JSON.parse(),这是ECMA-262第五版(JS所基于的规范)中定义的。它的用法很简单:

var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);
alert(obj.count);

对于没有的浏览器,您可以使用json2.js.来实现它

正如评论中所指出的,如果您已经在使用jQuery,那么有一个$.parseJSON函数可以映射到JSON.parse(如果可用),或者在旧浏览器中映射到eval的形式。然而,这会执行额外的、不必要的检查,这些检查也是由JSON.parse执行的,所以为了获得最佳的全面性能,我建议这样使用它:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

这将确保您立即使用本机JSON.parse,而不是让jQuery在将字符串传递给本机解析函数之前对其进行健全性检查。

来源:用JavaScript解析JSON?