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

标签 ajax jquery

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

引用文献:http://api.jquery.com/jQuery.getJSON/

关于ajax - 为什么这个 jQuery Ajax 请求失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3671459/

相关文章:

php - 推荐一个分页程序 AJAX PHP

javascript - 如何从异步调用返回响应?

javascript - 使用jquery ajax函数报错 ' missing : after property id'

javascript - 如何通过 javascript Ajax POST 发送 html 表单的表单参数?

javascript - jQuery:在页面中心保留一个div,即使页面向下滚动

javascript - 在 JS/JQ 中动态加载时选择一个元素

javascript - "Uncaught TypeError: Cannot read property ' 将重复事件添加到数据库时克隆 ' of undefined"

javascript - 使用 ajax 提交表单会导致 Charset 出现奇怪的行为

javascript - 当我点击特定元素时如何找到text()?

javascript - 如何显示输入中选定行的信息?