Jquery请求总是失败

时间:2016-07-08 16:15:00

标签: javascript jquery

我目前正在使用暗天空预测api https://developer.forecast.io/通过jquery get request检索json对象。所需的url参数格式为(api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE")而带参数的有效格式为: https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115 在浏览器中输入此URL将显示一个json对象。

我尝试的第一件事是jquery get请求:

 $.ajax({
     type: 'GET'
     , data: ''
     , url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
     , success: function (data) {
         alert("works");

     }
     , datatype: 'json'


     , error: function (err) {
         alert("Could not get forecast");
     }

 });

这不成功 - 它会触发错误功能。我再次尝试使用帖子请求它也不起作用。请帮助

1 个答案:

答案 0 :(得分:3)

这是一个简单的CORS问题,可以使用jsonp数据类型轻松解决:



$.ajax({
  url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
  dataType: "jsonp",
  success: function(data) {
    console.log(data.latitude, data.longitude);
    console.log(data.timezone);
    console.log(data.daily.summary);
  },
  error: function(err) {
    console.log("Could not get forecast");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>
&#13;
&#13;
&#13;