[英]Using a variable as the URL in getJSON jquery
我正在使用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('℉');
});
});
使用瀏覽器中的開發人員工具。 查看控制台。 查看網絡標簽。 這樣可以清楚地表明您的URL導致404錯誤。
您的網址缺少該方案。 它的前面需要http://
或https://
。
當您在地址欄中鍵入URL(缺少方案)時,瀏覽器會自動插入http://
。
可能未將api設置為無法直接處理來自javascript的請求,通常您需要在服務器端編寫服務以與api通信,並向該服務發出AJAX請求,而不是直接向api發送請求。 默認情況下,跨域AJAX請求在瀏覽器中被阻止
實際上,如前所述,將您的網址更改為包括:
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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.