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 = f开发者_运维技巧unction(url) {
console.log("Recieved data from " + url);
};
xhr.send();
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);
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();
}
精彩评论