jQuery跨域请求获取没有回调的JSON响应

Ash*_*lix 11 ajax jquery cross-domain

我正在尝试从此URL检索JSON

http://www.iheartquotes.com/api/v1/random?format=json
Run Code Online (Sandbox Code Playgroud)

通过jQuery.我知道解决方案是JSONP,但由于我无法控制服务的响应文本或将其包装在我自己的回调函数中,我的目的是以某种方式使用客户端脚本检索上述URL的响应.

我已尝试从StackOverflow的几个答案中建议的几乎所有方法.这些是我尝试的代码块和我得到的响应.

1.直接调用返回预期的Access-Control-Allow-Origin错误

$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
   function(data) {
     alert(data);         
   });
Run Code Online (Sandbox Code Playgroud)

响应:

XMLHttpRequest无法加载= 1376682146029"> http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.Access-Control-Allow-Origin 不允许使用Origin http://stackoverflow.com.

2.添加了回调参数的上述代码:

$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
   function(data) {
     alert(data);         
   });
Run Code Online (Sandbox Code Playgroud)

响应:

未捕获的SyntaxError:意外的令牌:

请注意,当我单击错误时,它会转到我预期的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"}
Run Code Online (Sandbox Code Playgroud)

这也是预期的,因为响应中没有定义回调函数.

3.通过jQuery的Ajax方法

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://www.iheartquotes.com/api/v1/random?format=json",
   success: function(data){        
     alert(data);
   },
});
Run Code Online (Sandbox Code Playgroud)

响应:

未捕获的SyntaxError:意外的令牌:

将回调参数添加到上述函数不会更改响应.

来自专家的任何帮助或指示从URL检索JSON?我正在使用Chrome开发工具对此进行测试.我知道我可以从服务器端代码调用该服务,然后将其发送到客户端.但我想看看是否可以通过客户端单独的jQuery来完成.

编辑:基于Kevin B的评论:使用jQuery的Ajax通过YQL获得预期的输出.但我的问题仍然是一样的.是否存在通过jQuery执行此操作的本机方式,因为YQL仍然是依赖项?

// 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
    }
});
Run Code Online (Sandbox Code Playgroud)

这给出了预期的响应.

wil*_*ing 1

这不适用于所有浏览器,但取决于您使用的 JQuery 版本,请尝试:

$.support.cors = true;
Run Code Online (Sandbox Code Playgroud)

显然这也取决于服务器响应的标头。