同时xhr请求的最大数量?

时间:2015-01-31 13:10:06

标签: javascript xmlhttprequest

我正在制作一个小型网络应用,允许用户拖动滑块以显示不同的内容。每次移动滑块时,客户端都使用HTML5 Geolocation来获取其位置,然后将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);
    },
};

所以你可以看到我在发送请求函数周围有一个try-catch。当我快速移动Slider很多次时,这些是我在ff和chrome中得到的错误信息。

  • Firefox:“错误消息:[例外...”失败“nsresult: “0x80004005(NS_ERROR_FAILURE)”位置:“JS frame :: http://localhost/ *** / myscript.js :: sendRequest ::第29行“数据: 没有]“

  • Chrome:“错误消息:DOMException:无法执行'发送' 'XMLHttpRequest':对象的状态必须是OPENED。“

我在Wampserver2上尝试这个(它使用Apache服务器)。

所以我的问题是:什么是错的? 我在某处读到浏览器只允许同时提供一定数量的xhr请求(如果记得正确则大约为6-7)。虽然如果我快速拖动滑块3-4次就可以得到这个错误,那么这可能是个问题吗?有更好的方法吗?

编辑: 添加了updatePosition()函数。它在命名空间中称为Geoposition。

编辑2: 如果你因为标题来到这里,这个问题与我怀疑的“最大同时xhr请求数量”无关。

1 个答案:

答案 0 :(得分:1)

除了implicit global而不是您的本地sendRequestFunction属性,您不得在异步GeoLocation方法中使用自由变量。后续调用将覆盖之前的值,稍后调用updatePosition回调时,每个回调都将调用相同的getCurrentPosition。这对您的sendRequestFunction对象是致命的,因为它不喜欢多次发送(这就是错误消息所说的,请求处于xhr无效的状态)

send()

另外,您可能需要考虑限制地理定位和ajax调用。

相关问题