XHR在onreadystatechange中获取请求URL

时间:2011-01-12 21:01:16

标签: javascript ajax xmlhttprequest

有没有办法在“onreadystatechange”方法中获取请求的URL?

我想运行多个XHR请求并知道它们中的哪一个回来了:

xhr.open("GET", "https://" + url[i], true);
xhr.onreadystatechange = function(url) {
    console.log("Recieved data from " + url);
};
xhr.send();

2 个答案:

答案 0 :(得分:5)

有三种简单的方法可以做到这一点。

1:使用已经描述的闭包

2:在xhr对象上设置一个属性,稍后可以像这样引用:

xhr._url = url[i];
xhr.onreadystatechange = function(readystateEvent) {
    //'this' is the xhr object
    console.log("Recieved data from " + this._url);
};
xhr.open("GET", "https://" + url[i], true);

3:将您需要的数据存入您的回调(我的首选解决方案)

Function.prototype.curry = function curry() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function curryed() {
        return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
    };
};

function onReadystateChange(url, readystateEvent) {
  console.log("Recieved data from " + url);
};

xhr.onreadystatechange = onReadystateChange.curry(url[i]);
xhr.open("GET", "https://" + url[i], true);

答案 1 :(得分:4)

使用closures

function doRequest(url) {
    // create the request here

    var requestUrl = "https://" + url;
    xhr.open("GET", requestUrl, true);
    xhr.onreadystatechange = function() {

        // the callback still has access to requestUrl
        console.log("Recieved data from " + requestUrl); 
    };
    xhr.send();
}