[英]callback function doesn't work when using getJSON function in jQuery
[英]I can't change an HTML element's contents through the callback to the jquery function $.getJSON()
我正在嘗試將id屬性為country (即id="country"
)的div元素的內容更改為用戶當前位置的國家/地區。 我的代碼有什么問題嗎?
function location (position){
var a=position.coords.latitude;
var b=position.coords.longitude;
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat='+a+'&lon='+b+'&APPID=b84cde4a2b80a14ecfebbd9ea7d08831&units=metric', function getData(data){
$("#country").html(data.sys.country);
})
}
編輯
值得一提的是,從Chrome 50開始,Geolocation API僅適用於安全上下文,例如HTTPS。
如果您的網站托管在非安全來源(例如HTTP)上,則獲取用戶位置的請求將不再起作用。
如果您使用HTTPS,
原版的
我猜您沒有正確建立位置對象。
確保您有一個position
對象,該對象具有一個名為coords
的屬性,該對象的值具有兩個屬性,即緯度和經度。 每個對象都必須用{ }
封裝
在以下代碼段中效果很好(原始代碼未更改):
function location(position) { var a = position.coords.latitude; var b = position.coords.longitude; $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + a + '&lon=' + b + '&APPID=b84cde4a2b80a14ecfebbd9ea7d08831&units=metric', function getData(data) { $("#country").html(data.sys.country); }) } /* here we build our position object with a coords child object containing latitude and longitude */ var pos = { "coords": { "latitude": 34.7459360, "longitude": -118.2506350 } }; /* now we actually call the script location(pos) using our position object */ location(pos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="country"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.