小编典典

AJAX调用并清除JSON,但语法错误:缺少; 声明前

ajax

我正在使用以下代码进行跨域JSONP调用:

jQuery.ajax({
        async: true,
        url: 'http://mnews.hostoi.com/test.json',
        dataType: 'jsonp',
        method: "GET",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            if (data.Error || data.Response) {
                exists = 0;
            }
        }
    });

在Firebug中进行调试时,出现以下错误:

在此处输入图片说明

SyntaxError: missing ; before statement

但是,当我通过jsonlint.com之类的工具传递我的json对象(可通过JQ代码中的链接获得)时,它说这是有效的JSON。而且我也没有发现任何异常。它怎么可能返回语法错误?是我没有得到的一些JSONP详细信息还是什么?

JSON样本

{"news":[ {
  "sentences": [
    "Neuroscientists have discovered abnormal neural activity...", 
    "The researchers found that these mice showed many symptoms...", 
    "\"Therefore,\" the study authors say, \"our findings provide a novel.."
  ], 
  "summaryId": "ZJEmY5", 
  "title": "Abnormal neural activity linked to schizophrenia"
}]}

提前致谢。


阅读 257

收藏
2020-07-26

共1个答案

小编典典

JSONP不是JSON。JSONP响应将由一个JavaScript脚本组成,该JavaScript脚本仅包含一个函数调用(对预定义函数)和一个参数(这是符合JSON语法的JavaScript对象文字)。

您得到的响应是JSON,而不是JSONP,因此您将其作为JSONP处理的工作失败。

更改dataType: 'jsonp'dataType: 'json'(或完全删除该行,服务器将发出正确的内容类型,因此您无需覆盖它)。

由于您的脚本在JSON之外的其他来源上运行,因此您还需要采取步骤(大多数(但不是全部)都需要您控制服务于JSON的主机)来解决同一来源策略

2020-07-26