检索跨域JSON数据,Javascript / JSON

时间:2016-06-30 21:59:21

标签: javascript json ajax jsonp

我做了一些关于检索跨域JSON数据的研究,但是当我实现它时,代码并没有起作用。做了一些研究,我发现浏览器不允许网站出于安全原因从其他主机检索数据。我找到了一个答案,说我应该使用JSONP,但它仍然无法正常工作?这是我的代码。

function getWeather(location){
   $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=/*my usual app id is here*/&callback=?", function(result){
       //response data are now in the result variable
       alert(result.weather[0].description);
       var changeW = document.getElementById("theweathertext");
       changeW.innerHTML = "The current weather at your destination: " + result.weather[0].description +".";
});
}

当我测试代码时,浏览器不允许我检索数据?我该如何解决这个问题?提前谢谢。

更新:当我在本地测试时,此代码正常工作,但当我进行实时启动预览时,它无法正常工作。这可能是其他问题吗?

1 个答案:

答案 0 :(得分:0)

我认为如果您提供有效的apikey,此代码将起作用:

$.getJSON(
    'http://api.openweathermap.org/data/2.5/weather?q=lisbon&callback=?',
    function(data){
        console.log(data);
    }
);

编辑:它目前给我401代码,这意味着我无权访问此端点。这就是为什么我建议使用有效的api密钥。