【问题标题】:jQuery Cross Domain Request to get JSON Response without CallbackjQuery 跨域请求获取 JSON 响应而无需回调
【发布时间】:2013-08-19 07:47:21
【问题描述】:

我正在尝试从此 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 无法加载 =1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029。 来源http://stackoverflow.com 不允许 访问控制允许来源。

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 完成。

编辑: 基于凯文 B 的评论: 使用 jQuery 的 Ajax 通过 YQL 获得预期的输出。但我的问题还是一样。由于 YQL 仍然是一个依赖项,有没有一种通过 jQuery 实现的本地方法?

// 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
    }
});

这给出了预期的响应。

【问题讨论】:

  • 没有服务器端干预是不可能的。请注意,它不必是 your 服务器,google YQL。
  • 或者看这里的文章:learn.jquery.com/ajax/working-with-jsonp
  • 嘿@KevinB,非常感谢 YQL 指针。在某种程度上,你的建议奏效了。我也编辑了我的问题以包含新代码。
  • 喜欢斜体的“你的”:P 整个事件的关键。
  • select * from json 我认为会给你一个更好的回应,尽管它当然仍然是一个依赖项。

标签: ajax jquery cross-domain


【解决方案1】:

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

$.support.cors = true;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2011-03-13
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多