【问题标题】:Using a variable as the URL in getJSON jquery在getJSON jquery中使用变量作为URL
【发布时间】:2016-02-22 21:28:42
【问题描述】:

我正在使用 jquery 创建一个天气应用程序。我遇到的问题是在我的 getJSON 中,我想使用我使用您当前的纬度和经度坐标创建的变量。带有我的 openweather api 密钥的 url 在浏览器中加载 json 文件就好了,但它似乎不想在我的 getJSON 中工作。

这是我的 javascript 代码,用于根据您的位置显示天气信息。

var lat;
var lon;
var jsonURL;

  navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
    lat = location.coords.latitude;
    lon = location.coords.longitude;

    jsonURL = 'api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&APPID=example&units=imperial'

}



$("#getWeather").click(function(){
  console.log(jsonURL);
    $.getJSON(jsonURL , function( data ) {
    var items = [];
    items = data;   $("#weather").text(items.main.temp).append('℉');
    });
});

【问题讨论】:

  • 请删除任何敏感数据,例如您的APPID

标签: javascript jquery json api


【解决方案1】:

使用浏览器中的开发者工具。查看控制台。查看网络选项卡。这将清楚地表明您的 URL 导致了 404 错误。

您的网址缺少该方案。前面需要http://https://

当您在地址栏中键入 URL(缺少方案)时,浏览器会自动插入 http://

【讨论】:

    【解决方案2】:

    可能 api 没有设置为直接处理来自 javascript 的请求,您经常需要在服务器端编写一个服务来与 api 通信,并将 AJAX 请求发送到该服务而不是直接发送到api。浏览器默认阻止跨域 AJAX 请求

    【讨论】:

      【解决方案3】:

      实际上如上所述更改您的网址以包含:

          jsonURL = 'http://api.openweathermap.org/data/...'
      

      并将其设为“JSOP”格式:

              $("#getWeather").click(function() {
                $.getJSON(jsonURL, {
                    format: "jsonp"
                  })
                  .done(function(data) {
                    console.log(data);
                  }).fail(function(jqxhr, textStatus, error) {
                    var err = textStatus + ", " + error;
                    console.log("Request Failed: " + err);
                  });
              });
      

      【讨论】:

      • 谢谢,但在这种情况下它不需要是 jsonp
      猜你喜欢
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      相关资源
      最近更新 更多