XHR在onreadystatechange中获取请求URL

Rad*_*mko 3 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();
Run Code Online (Sandbox Code Playgroud)

Mar*_*sen 5

有3种简单的方法可以做到这一点.

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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)