【问题标题】:Div text doesn't change to API propertydiv 文本不会更改为 API 属性
【发布时间】:2016-05-21 20:43:45
【问题描述】:

我正在做 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, 即使通过黑暗天空预报,我也可以看到我的回电已收到, 谢谢!

【问题讨论】:

  • 该 url 不发送允许跨域请求的 CORS 标头,因此您的 success 回调将无法到达。您应该在控制台上看到一条关于它的消息。它似乎确实允许 JSONP 响应
  • 谢谢!但是我试过了,还是不行,你能帮我处理一下代码吗?

标签: javascript jquery


【解决方案1】:

-按照@Martin Gottweis 的建议修复了CORS 问题。 (ip-api不需要回调,但是预测的可以)

-在你的预测getJSON函数中,你检索.currently,但它只是一个内部有更多数据的对象,你必须指定你想要的(例如.summary)。

-将代码从预测 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);
            });
        });
    }); 

【讨论】:

  • 谢谢!我被困了一天!
【解决方案2】:

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

$(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

【讨论】:

  • 谢谢!但它仍然无法在 codePen 上运行,你知道为什么吗?我已经坚持了大约 5 个小时
  • codepen.io/anon/pen/zqgxjJ?editors=1111 ap-api 有效,但预测无效。你是怎么得到链接的?你必须使用那个天气 api 吗?
  • 不,我没有,但是 FCC 建议的 api 不起作用,所以我寻找另一个,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 1970-01-01
相关资源
最近更新 更多