5

Is there any way to get the URL of request in the "onreadystatechange" method?

I want to run multiple XHR requests and know which of them comes back:

xhr.open("GET", "https://" + url[i], true);
xhr.onreadystatechange = function(url) {
    console.log("Recieved data from " + url);
};
xhr.send();
keza
  • 2,601
  • 2
  • 16
  • 10
Radek Simko
  • 15,886
  • 17
  • 69
  • 107

2 Answers2

5

There are 3 simple ways of doing this.

1: use closures as already described

2: set an attribute on the xhr object that you can reference later like so:

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: Curry the data you need into your callbacks (my preferred solution)

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);
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
4

Use 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();
}
Community
  • 1
  • 1
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112