【问题标题】:Why am I getting a parseerror when using jQuery's ajax()?为什么在使用 jQuery ajax() 时出现解析错误?
【发布时间】:2012-01-26 11:11:30
【问题描述】:

谁能告诉我为什么我在控制台中不断收到以下代码的解析错误?

$.ajax({
    url : "file.php",
    data : data,
    dataType : "json",
    success : function (request) {
        console.log("success");
    },
    error : function (request, error) {
        console.log(error);
    }
});

我已经通过 jsonlint.com 验证了我的 JSON,它是有效的。

在 Firebug 的 Net 选项卡中返回的响应标头是:

内容长度 19

保持活动超时=5,最大值=96

连接保持活动

内容类型应用程序/json

【问题讨论】:

  • 您在 Firebug 的“网络”选项卡中看到了什么?
  • 错误中有更多细节吗?
  • 您发布的代码没有抛出任何错误,您得到的确切错误是什么?也许表单输入的名称或值(我猜)包含无效字符。
  • 你用的是什么版本的jQuery?
  • 您是否尝试将dataType 更改为text?然后您应该能够console.log 返回数据。

标签: javascript jquery ajax json parse-error


【解决方案1】:

这就是你可以从 PHP 发送 json 的方式

$response = array("title" => "One");

echo json_encode($response);

如果 { "title": "One" } 是响应,响应的 Content-Length 应该是 18,但是从你的描述我可以看出它是19。所以响应json字符串有问题,请检查。

【讨论】:

  • 从截图中我可以理解的是响应是json但是字符串编码在json中。通常当我们这样做时会发生这种情况echo json_encode('{ "title": "One" }'); 您可以将内容类型设置为 json 并使用 echo '{ "title": "One" }; 或制作响应对象并将其编码为 json 并使用 echo 像这样$response = array("title" => "One"); echo json_encode($response);
  • 感谢您的帮助。原来我的 PHP 文件有错误。
【解决方案2】:

thisnamevalue 似乎可能包含无效字符。与其编写自己的 data 字符串不如让 jQuery 为你做这件事:

data  = $this.serialize();

【讨论】:

  • @Zoolander 我知道你发布了声明dataType : 'json' 的代码,但我只需要检查一下,你没有设置dataType : 'jsonp' 是吗?因为如果dataType 设置不正确,响应几乎肯定会产生解析错误...
  • @Zoolander 也许设置contentType: "application/json; charset=utf-8"?
  • @Zoolander 怎么样:$.getJSON('file.php', data, function (response) {console.log('success');});?
猜你喜欢
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多