检索跨域JSON数据,Javascript/JSON

Retrieving cross-domain JSON data, Javascript/JSON

本文关键字:JSON Javascript 数据 检索      更新时间:2023-09-26

我做了一些关于检索跨域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 +".";
});
}

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

更新:当我在本地测试它时,这段代码是工作的,但是当我做一个实时发布预览时,它不起作用。会不会是别的问题?

我认为这段代码将工作,如果你提供一个有效的apikey:

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

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