我试图将我的位置作为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'中建立你的逻辑。 –