我正在制作一个小的web应用程序,允许用户拖动滑块来显示不同的内容。每次移动滑块时,客户端使用HTML5地理位置获取其位置,然后向服务器发送一个XMLHttpRequest以获取新内容。
问题是,如果用户移动滑块的次数太多,速度太快,就会导致错误。
代码:
function update(){
var xhr = new XMLHttpRequest();
var url = "request_handler.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var return_data = xhr.responseText;
//doing stuff
}
}
// since HTML5 Geolocation is a asynchronous function, and i have to make
// sure that i get the users clients position before i send the request, i
// pass the sendRequest function below as a callback function to the
// Geolocation function
function sendRequest(latitude,longitude) {
try{
xhr.send("latitude=" + latitude + "&longitude=" + longitude);
console.log("Success")
}
catch(err){
console.log("Error message: %s",err);
}
}
//This function gets user position and then calls sendRequest if it was
//Successfull
Geoposition.updatePosition(sendRequest);
}
//EDIT:
var Geolocation = {
sendRequestFunction: null,
options: {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
},
success: function(pos) {
if (sendRequestFunction) {
sendRequestFunction(pos.coords.latitude, pos.coords.longitude);
};
},
error: function(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
},
updatePosition: function(callbackFunction) {
sendRequestFunction = callbackFunction;
navigator.geolocation.getCurrentPosition(Geolocation.success, Geolocation.error, Geolocation.options);
},
};因此,正如您所看到的,我在发送请求函数周围有一个尝试捕获。当我快速移动滑翔机时,这些都是我在ff和chrome中得到的错误消息。
我正在Wampserver2上尝试这一点(它使用Apache服务器)。
所以我的问题是:出什么事了?我在某个地方读到,浏览器同时只允许一定数量的xhr请求(如果记住正确的话,大约是6-7 )。虽然我可以得到这个错误,如果我只拖曳滑块3-4次,这是无论如何?有没有更好的方法来解决这个问题?
编辑:添加了updatePosition()函数。它是在命名空间中,我称之为地理位置。
编辑2:如果你在这里是因为标题,这个问题与我怀疑的“最大数量的同时xhr请求”无关。
发布于 2015-01-31 16:12:20
除了sendRequestFunction是隐式全局而不是本地GeoLocation属性之外,还不能在异步updatePosition方法中使用空闲变量。随后的调用将覆盖前一个值,当稍后调用getCurrentPosition回调时,每个调用都将调用相同的sendRequestFunction。这对您的xhr对象是致命的,因为它不喜欢被多次发送(这正是错误消息说的,请求处于send()无效的状态)。
var Geolocation = {
options: {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
},
error: function(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
},
updatePosition: function(callbackFunction) {
navigator.geolocation.getCurrentPosition(function(pos) {
if (typeof callbackFunction == "function") {
callbackFunction(pos.coords.latitude, pos.coords.longitude);
}
}, Geolocation.error, Geolocation.options);
}
};此外,您可能需要考虑节流您的地理定位和ajax调用。
https://stackoverflow.com/questions/28251955
复制相似问题