FCC最近推出了一个小set of API calls to access FCC data 。我特别对 Consumer Broadband Test API 感兴趣。我正在尝试通过 jQuery 访问此 API,但失败了。如果我的代码有问题或者这似乎是 FCC 的 API 的问题,请告诉我。
如果您在浏览器中访问此 API 请求,它会正常返回 XML 响应:http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999
所以我尝试使用各种方法在 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);
});
在 Firebug 控制台中,所有三个请求均显示 200(正常)状态,但响应正文为空。此外,生成的 console.log
消息是:
ajax:
getJSON: null
get:
我在这里做错了什么吗?
最佳答案
要解决同源策略,您需要使用 JSONP。 It is supported通过 API。将 callback=?
添加到 .getJSON()
调用中的 URL 字符串:
If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
所以,像这样:
var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
// do stuff
});
关于ajax - 为什么这个 jQuery Ajax 请求失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3671459/