jQuery AJAX 调用并清理 JSON 但语法错误:丢失;声明前

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19456146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:00:48  来源:igfitidea点击:

AJAX call and clean JSON but Syntax Error: missing ; before statement

javascriptjqueryajaxjsonjsonp

提问by JZweige

I am making a cross domain JSONP call using this code:

我正在使用以下代码进行跨域 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;
            }
        }
    });

When debugging in Firebug, I get the following error:

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

enter image description here

在此处输入图片说明

SyntaxError: missing ; before statement

However, when I pass my json object (available through the link in the JQ code) through a tool like jsonlint.com, it says it is valid JSON. And I don't find any anomalies either. How could it be returning a syntax error? Is it some JSONP detail I am not getting or what?

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

JSON Sample

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"
}]}

Thanks in advance.

提前致谢。

采纳答案by Quentin

JSONP is not JSON. A JSONP response would consist of a JavaScript script containing only a function call (to a pre-defined function) with one argument (which is a JavaScript object literal conforming to JSON syntax).

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

The response you are getting is JSON, not JSONP so your efforts to handle it as JSONP fail.

您得到的响应是 JSON,而不是 JSONP,因此您在 JSONP 时处理它的努力失败了。

Change dataType: 'jsonp'to dataType: 'json'(or remove the line entirely, the server issues the correct content-type so you don't need to override it).

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

Since your script is running on a different origin to the JSON then you will also need to take steps(most, but not all, of which require that you control the host serving the JSON) to work around the same origin policy.

由于您的脚本在与 JSON 不同的来源上运行,因此您还需要采取措施(大多数但不是全部,其中要求您控制提供 JSON 的主机)来解决相同的来源策略

回答by epascarello

The error is because it is returning JSON not JSONP.

错误是因为它返回 JSON 而不是 JSONP。

JSONP is supposed to look like

JSONP 应该看起来像

someCallBackString({ The Object });

回答by whitesiroi

Here is the working example

这是工作示例

$.ajax({
 type: 'GET',
 url: 'http://xxx.amazonaws.com/file.json',
 dataType: 'jsonp',
 jsonpCallback: 'callback',
 success: function(json){
   console.log(json);
 }
});

And you should put callbackin the beginning of your file.jsonlike :

你应该把callback你的file.json喜欢放在开头:

callback({"item":{".......

callback({"item":{".......

回答by shasi kanth

As epascarello pointed out, the JSONP response must be sent like:

正如 epascarello指出的那样,JSONP 响应必须像这样发送:

callBackFunction({ JSON Object })

And the caller function can then be setup like:

然后可以像这样设置调用者函数:

var url =  "http://someremoteurl.com/json";
    $.getJSON(url + "?callback=?", null, function(data) {
    callBackFunction(data);
});

Then you can loop over the response data as:

然后你可以循环响应数据:

function callBackFunction(data)
{
   console.log(data);
}

回答by Andrew Bursov

If you're using "callback=?" parameter, your response on the server side should look like this:

如果您使用“ callback=?”参数,您在服务器端的响应应如下所示:

$_callback = $_GET['callback'];    
echo $_callback . '(' . json_encode(YOUR_VARIABLE) . ');';

If "callback=?" parameter is not defined, your response should look like this:

如果未定义“ callback=?”参数,您的响应应如下所示:

echo '[' . json_encode($_return_array) . ']';

回答by Arman Ortega

If the question is related to Ruby then in your controller make sure that you render the format correctly. example:

如果问题与 Ruby 相关,则在您的控制器中确保正确呈现格式。例子:

def view_product
   data = Product.find params[:id]
   render :json =>  data, :callback => params[:callback]
end

In your render method, you should have the :callbackparameter otherwise it will render in json instead of jsonp.

在您的渲染方法中,您应该有:callback参数,否则它将在 json 而不是 jsonp 中渲染。