我試圖將我的位置作爲Ajax請求發送。
可能是由於地理定位的異步調用,它不能按預期工作。 地理定位的功能在我的外部功能之後被調用,導致data is empty
的答案。地理定位異步調用的問題
$(document).ready(function() {
$("button").click(function() {
var data = "";
if (...) { // if user wants to share their location
function geo_success(position) {
console.info("lat:" + position.coords.latitude + " Lot: " + position.coords.longitude);
data = {
lat : position.coords.latitude,
lon : position.coords.longitude
};
}
function geo_error() {
alert("No position available.");
}
var geo_options = {
enableHighAccuracy : true,
timeout : 1000,
maximumAge : 0
};
navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options);
}
if (...) { // if user doesn't want to share their location
data = {
a : "abc", // some other data
b : "def"
};
}
if (...) { // maybe a third option
data = {
b : "test", // some other data
c : "some data"
};
}
if (Object.keys(data).length > 0) {
console.info("hier");
$.ajax({
method : "GET",
url : "test.php",
data : data, // finaly send data
dataType : 'json',
success : function(data) {
console.log(data)
},
error : function(data) {
console.error(data);
}
});
} else {
console.error("data is empty");
}
});
});
<input type="checkbox" id="box1" />
<button>ok</button>
我不能把Ajax請求的geo_success
,因爲要首先定義data
需求。在我的原始代碼中(這裏只是一個摘錄),根據用戶的選擇,有幾種可能的data
。
所以我只想要1個Ajax請求。
什麼可能是一種可能的補救措施?
*「我無法將Ajax請求放入geo_success中,因爲我需要首先定義數據。」* - 我無法看到這兩件事情是如何相關的。 – JJJ
設置'data'後,將ajax放入geo_success中 –
創建'promise',它將在'geo_success'中解析並在'geo_error'中被拒絕。然後在'.then'或'.catch'中建立你的邏輯。 –