Jquery 更新对象属性时出现问题
Jquery 更新对象属性时出现问题,jquery,Jquery,lon和lat值应该通过调用浏览器的地理定位服务来更新。Console.log语句显示地理定位在if/else块中工作正常,但是coords.lon和coords.lat没有更新。这可能是一个范围问题吗?想法 $(document).ready(function () { // object to hold user coordinates var coords = { lat: 0, lon: 0 }; // retrieve and set user
lon
和lat
值应该通过调用浏览器的地理定位服务来更新。Console.log语句显示地理定位在if/else块中工作正常,但是coords.lon
和coords.lat
没有更新。这可能是一个范围问题吗?想法
$(document).ready(function () {
// object to hold user coordinates
var coords = {
lat: 0,
lon: 0
};
// retrieve and set user's latitude and longitude coordinates
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition( function (position) {
coords.lon = position.coords.longitude;
coords.lat = position.coords.latitude;
});
} else {
alert("Sorry, I couldn't locate you. Here's the weather in Paris, France.");
coords.lon = 48.8566;
coords.lat = 2.3522;
}
// enumerate AJAX request settings & pass in coordinate settings
var ajaxOptions = {
crossDomain:true,
dataType:"json",
url:"https://fcc-weather-api.glitch.me/api/current?",
data: {
lon:coords.lon,
lat:coords.lat
},
method:"GET",
success: function (json) {
$("#description").html(JSON.stringify(json));
alert(coords.lat);
},
error: function () {
alert("Ajax request failed");
}
};
// make AJAX request by passing in options specified in object above
$.ajax(ajaxOptions);
getCurrentPosition()
是异步的。您正试图在收到数据之前使用数据发出ajax请求。当geolocation
不可用时,在getCurrentPosition
回调中发出ajax请求,您知道您有数据…或者在else
中发出ajax请求
为了使读起来更清晰,将把ajax封装在一个可以从那里调用的函数中
// default coordinates - Paris
let coords = {
lon: 48.8566,
lat: 2.3522
}
// retrieve and set user's latitude and longitude coordinates
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
coords.lon = position.coords.longitude;
coords.lat = position.coords.latitude;
// do request with user location coords
doAjax(coords);
});
} else {
alert("Sorry, I couldn't locate you. Here's the weather in Paris, France.");
// do request using default coords
doAjax(coords);
}
function doAjax(coords) {
// enumerate AJAX request settings & pass in coordinate settings
var ajaxOptions = {
crossDomain: true,
dataType: "json",
url: "https://fcc-weather-api.glitch.me/api/current?",
data: {
lon: coords.lon,
lat: coords.lat
},
method: "GET",
success: function(json) {
$("#description").html(JSON.stringify(json));
alert(coords.lat);
},
error: function() {
alert("Ajax request failed");
}
};
// make AJAX request by passing in options specified in object above
$.ajax(ajaxOptions);
}