无法解析来自jquery Ajax Call的JSON响应

时间:2022-10-07 17:05:14

I'm relatively new to jquery/ajax, and I'm having trouble parsing the results from a very simple JSON ajax call. Here's my code. There are 2 test URLs in this example: the commented URL works as expected, but the uncommented URL does not (they are both properly formatted JSON, according to jslint). Any idea why one would throw a parse error, and the other would not (they are both 3rd party domains)?

我对jquery / ajax比较陌生,而且我很难从一个非常简单的JSON ajax调用中解析结果。这是我的代码。此示例中有2个测试URL:注释的URL按预期工作,但未注释的URL不符合(根据jslint,它们都是格式正确的JSON)。知道为什么会抛出一个解析错误,另一个不会(它们都是第三方域)?

Thank you in advance!

先感谢您!

function getNews2() {

$.ajax({

    //url: "http://api.ihackernews.com/page?format=jsonp",
    url: "http://recs.coremetrics.com/iorequest/restapi?cm_cid=90232642&cm_zoneid=Mobile&cm_targetid=FULO-0101",
    dataType: "jsonp",
    success: function(data, textStatus, xhr) {
        alert("SUCCESS recsStatus=" + textStatus);
        alert(JSON.stringify(data));
    },
    error: function(data, textStatus, errorThrown) {
        alert("FAILURE recsStatus=" + textStatus);
        alert(JSON.stringify(data));
    }
});
}

getNews2();

1 个解决方案

#1


2  

after looking at responses from both URLs with CURL, the one that doesn't work is not a jsonp response. It's a json response. It's not wrapped in the method call required by json p to work.

在使用CURL查看来自两个URL的响应之后,不起作用的那个不是jsonp响应。这是一个json的回应。它没有包含在json p工作所需的方法调用中。

The one that doesn't work is

不起作用的是

{"io":{"rec_count":12,...}}

vs

HNCallback({"nextId":null,...})

see the difference?

看到不同?

You won't be able to get a pure json response from either URL because of the same origin policy. So you need to use CORS (if you control the other domains), or jsonp, like you are currently configured to use, or server side proxy.

由于原始策略相同,您将无法从任一URL获得纯json响应。因此,您需要使用CORS(如果您控制其他域)或jsonp,就像您当前配置使用的那样,或服务器端代理。

#1


2  

after looking at responses from both URLs with CURL, the one that doesn't work is not a jsonp response. It's a json response. It's not wrapped in the method call required by json p to work.

在使用CURL查看来自两个URL的响应之后,不起作用的那个不是jsonp响应。这是一个json的回应。它没有包含在json p工作所需的方法调用中。

The one that doesn't work is

不起作用的是

{"io":{"rec_count":12,...}}

vs

HNCallback({"nextId":null,...})

see the difference?

看到不同?

You won't be able to get a pure json response from either URL because of the same origin policy. So you need to use CORS (if you control the other domains), or jsonp, like you are currently configured to use, or server side proxy.

由于原始策略相同,您将无法从任一URL获得纯json响应。因此,您需要使用CORS(如果您控制其他域)或jsonp,就像您当前配置使用的那样,或服务器端代理。