Div文本不会更改为API属性

时间:2016-05-21 20:43:46

标签: javascript jquery

我正在进行FCC前端认证,我无法正确处理api:

$(document).ready(function() {

  $.getJSON("http://ip-api.com/json/", function(data) {
    var city = data.city;
    lat = data.lat;
    long = data.lon;
    $("#long").text("The weather for  " + city + " is:");
    url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/" + lat + "," + long;
    $.getJSON(url, function(data) {
      temp = data.currently;
      $("#tmp").text("b");
    });
    $("#tmp").text(temp);
  });
  $("#tmp").text(temp);
}); 

但是,tmp不会将其文本更改为var temp, 即便是通过黑暗天空预测,我可以看到我的回调已收到, 谢谢!

2 个答案:

答案 0 :(得分:1)

- 修复CORS问题,因为@Martin Gottweis建议你。 (ip-api不需要回调,但预测一个是)

- 在您的预测getJSON函数中,您检索.currently,但它只是一个内部有更多数据的对象,您必须指定所需内容(例如.summary)。< / p>

- 从预测getJSON之外移动代码,以便它可以访问temp变量。

    $(document).ready(function() {
        $.getJSON("http://ip-api.com/json/", function(data) {
            var city = data.city;
            lat = data.lat;
            long = data.lon;
            $("#long").text("The weather for  " + city + " is:");
            url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/" + lat + "," + long + "?callback=?";
            $.getJSON(url, function(data) {
                temp = data.currently.summary;
                $("#tmp").text(temp);
            });
        });
    }); 

答案 1 :(得分:0)

问题在于@PatrickEvans提到的cors。试试这个hombre:

$(document).ready(function() {
    $.getJSON("http://ip-api.com/json/?callback=?", function(data) {
    console.log(data)
        var city = data.city;
        lat = data.lat;
        long = data.lon;
        $("#long").text("The weather for  " + city + " is:");
        url = "https://api.forecast.io/forecast/b537d8225ba7eaa6a34d16afbae307c3/?" + lat + "," + long + "&callback=?";
        $.getJSON(url, function(data) {
            var temp = data.currently;
            $("#tmp").text("b");
        });
        $("#tmp").text(temp);
    });
    $("#tmp").text(temp);
});

另外,请阅读jsonp