【问题标题】:Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)相同数据的 Ajax 错误(parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)
【发布时间】:2015-02-15 07:22:32
【问题描述】:

我有两个页面使用相同的 js 文件来调用某个 PHP 文件并从那里以 JSON 格式获取数据。虽然进入 PHP 文件的数据与输出的数据完全相同,但 Ajax 在第二页返回 'parsererror' SyntaxError: JSON.parse: unexpected character at line 1 column 1 JSON 数据。

        $.ajax({
        type: 'POST',
        dataType: "json",
        data: {objtyp: this.objtyp, objid: this.objid},
        url: '/admin/getfieldsadd.php', 
        success: function(data) {
        //not going to happen
        },

        error: function (xhr, status, text) {
          switch (status) {
             case 404:
                 alert('File not found');
                 break;
             case 500:
                 alert('Server error');
                 break;
             case 0:
                 alert('Request aborted');
                 break;
             default:
                 alert('Unknown error: ' + status + " " + text);
            }
        }

那么有人遇到过同样的问题吗?

【问题讨论】:

  • 查看开发者工具中的响应。确保响应中除了 JSON 之外没有任何内容。
  • @Barmar, here
  • @void,之前的评论。

标签: javascript php ajax json


【解决方案1】:

这听起来让人想起dreaded BOM。该链接的摘录:

在使用 Unicode 字符编码的页面的开头,您 可能会找到一些代表 Unicode 代码点 U+FEFF BYTE 的字节 ORDER MARK(简称BOM)。

正确使用时,BOM 是不可见的。

也许检查文件的编码是否设置为 UTF8 without BOM

【讨论】:

  • 虽然这是可能的,但更常见的原因是在调用 echo json_encode() 之前在脚本中打印一些内容。
  • @Barmar,你是什么意思? PHP 还是 JS 文件?
【解决方案2】:

可能是 MIME 类型错误。

尝试在您的 AJAX 调用中添加这样的 beforeSend 属性:

$.ajax({
    type: 'POST',
    dataType: "json",
    data: {objtyp: this.objtyp, objid: this.objid},
    url: '/admin/getfieldsadd.php',
    beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/json");
        }
    },
    ...
}

【讨论】:

  • 它没有帮助,唉。
【解决方案3】:

看来问题出在 jQuery 版本上。现在它已更新,一切似乎都可以正常工作。

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2016-05-16
    • 1970-01-01
    • 2018-02-03
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多