2016-12-04 194 views
-2

我想从openweathermap.org获取JSON数据,但$ .getJSON不起作用。 如果我从浏览器调用API,它将显示JSON数据,但它不适用于JS文件。无法获取天气API

$(document).ready(function(){ 
$("#button").click(function(){ 
    navigator.geolocation.getCurrentPosition(location,error,{timeout:10000});  
}); 
function location(pos){ 
    $("#crd").html("Location: " + pos.coords.latitude + " , " + pos.coords.longitude); 

    $.getJSON("api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){ 
     $("#weather").html(JSON.stringify(json)); 
    }); 

} 
function error(err){ 
    var errorCode = ""; 
    switch(err.code) { 
    case err.PERMISSION_DENIED: 
     errorCode = "User denied the request for Geolocation."; 
     break; 
    case err.POSITION_UNAVAILABLE: 
     errorCode = "Location information is unavailable."; 
     break; 
    case err.TIMEOUT: 
     errorCode = "The request to get user location timed out."; 
     break; 
    case err.UNKNOWN_ERROR: 
     errorCode = "An unknown error occurred."; 
     break;  
    } 
    $("#crd").html("Error " + err.code + ": " + errorCode); 
} 
}); 

还有一个问题。当我添加http://时它在localhost上工作,但它在codepen中不起作用。任何想法?

我发现,在codepen你需要使用一些跨域像https://cors-anywhere.herokuapp.com/

+1

你必须锚定的地址它要正确引用另一个域。你可以通过在开始处(和可选的协议)加入'//''//api.openweathermap.org/...“来实现。否则,地址被视为相对于当前页面,并且'api.openweathermap.org'也可以是有效的目录名称。 –

+0

如果您使用完整的URL(包括方案('http://'或'https://',或者可能只是'//使用当前方案))将是一个好主意 – jcaron

+1

请注意,在您最喜欢的浏览器的检测器/开发工具中请求可能会很快突出显示这个问题。 – jcaron

回答

1

你错过了sheme解决方案:尝试http://此:

$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&APPID=key", function(json){ 
    $("#weather").html(JSON.stringify(json)); 
}); 
+0

它工作。非常感谢。 – Viktor

+0

@Viktor没问题,请将答案标记为正确。 – mitch