简体   繁体   English

为什么这个jQuery Ajax请求失败?

[英]Why is this jQuery Ajax request failing?

The FCC recently made available a small set of API calls to access FCC data . FCC最近提供了一小部分API调用来访问FCC数据 In particular, I'm interested in the Consumer Broadband Test API . 我特别对Consumer Broadband Test API感兴趣。 I'm trying to access this API through jQuery but am failing. 我正在尝试通过jQuery访问此API,但是失败了。 Please let me know if I'm doing something wrong with my code or if this seems to be a problem with FCC's API. 如果我的代码有问题,或者FCC的API似乎有问题,请告诉我。

If you visit this API request in a browser, it returns a XML response just fine: http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999 如果您在浏览器中访问此API请求,它将返回一个XML响应: http : //data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999

So I've tried to load this data in jQuery using various methods: 因此,我尝试使用各种方法在jQuery中加载此数据:

var url = "http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999";

$.ajax({
    type: "GET",
    url: url,
    success: function(data) {
        console.log("ajax: " + data);
    }
});

$.getJSON(url, function(data) {
    console.log("getJSON: " + data);
});

$.get(url, function(data) {
    console.log("get: " + data);
});

In the Firebug console, all three requests show a 200 (OK) status, but the response body is empty. 在Firebug控制台中,所有三个请求均显示200(确定)状态,但响应正文为空。 Also, the resulting console.log messages are: 同样,生成的console.log消息是:

ajax: 
getJSON: null
get: 

Am I doing something wrong here? 我在这里做错了吗?

To work around the Same Origin Policy, you'll need to use JSONP. 要变通解决相同来源策略,您需要使用JSONP。 It is supported by the API. API 支持 Add callback=? 添加callback=? to the URL string in your .getJSON() call: .getJSON()调用中的URL字符串:

If the URL includes the string "callback=?" 如果URL包含字符串“callback =?” in the URL, the request is treated as JSONP instead. 在URL中,该请求将被视为JSONP。 See the discussion of the jsonp data type in $.ajax() for more details. 有关更多详细信息,请参见$ .ajax()中有关jsonp数据类型的讨论。

So, something like this: 所以,像这样:

var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
  // do stuff
});

References: http://api.jquery.com/jQuery.getJSON/ 参考: http : //api.jquery.com/jQuery.getJSON/

You can't make cross-domain calls using AJAX. 您无法使用AJAX进行跨域调用。 It doesn't work like that. 它不像那样工作。

What you probably want to do is to have your AJAX query URL be a local script on your own server, then have that script run a request for the API url (using cURL or something). 您可能想要做的是让AJAX查询URL成为您自己服务器上的本地脚本,然后让该脚本运行对API URL的请求(使用cURL或其他方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM