我正在尝试从此 URL 检索 JSON
http://www.iheartquotes.com/api/v1/random?format=json
通过 jQuery。我知道解决方案是 JSONP,但由于我无法控制服务的响应文本或将其包装在我自己的回调函数中,所以我的目标是使用客户端脚本以某种方式检索上述 URL 的响应。
我已经尝试了 StackOverflow 的几个答案中建议的几乎所有方法。 这些是我尝试过的代码块和我得到的响应。
1.返回预期 Access-Control-Allow-Origin 错误的直接调用
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json", function(data) { alert(data); });
回应:
XMLHttpRequest cannot load =1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
2.上面添加了回调参数的代码:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?", function(data) { alert(data); });
回应:
Uncaught SyntaxError: Unexpected token :
请注意,当我点击错误时,它会将我带到预期的 JSON 响应。
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
这也是预期的,因为响应中没有定义回调函数。
3.通过jQuery的Ajax方法
$.ajax({ type: "GET", dataType: "jsonp", url: "http://www.iheartquotes.com/api/v1/random?format=json", success: function(data){ alert(data); }, });
回应:
Uncaught SyntaxError: Unexpected token :
向上述函数添加回调参数不会更改响应。
专家有任何帮助或指导来从 URL 检索 JSON 吗?我正在通过 Chrome 开发工具对此进行测试。我知道我可以从服务器端代码调用该服务,然后将其发送到客户端。但我想看看这是否可以仅通过客户端的 jQuery 来完成。
编辑: 根据 Kevin B 的评论: 使用 jQuery 的 Ajax 通过 YQL 获得了预期的输出。但我的问题仍然是一样的。由于 YQL 仍然是一个依赖项,是否有一种通过 jQuery 实现的 native 方法?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
这给出了预期的响应。
最佳答案
这并不适用于所有浏览器,但取决于您使用的 JQuery 版本,请尝试:
$.support.cors = true;
显然这也取决于服务器响应的 header 。
关于ajax - jQuery跨域请求获取JSON响应而不回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281183/