Radek Simko
Radek Simko

Reputation: 16126

XHR get request URL in onreadystatechange

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();

Upvotes: 5

Views: 9019

Answers (2)

Martin Jespersen
Martin Jespersen

Reputation: 26183

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);

Upvotes: 5

Ivo Wetzel
Ivo Wetzel

Reputation: 46735

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();
}

Upvotes: 4

Related Questions