XHR在onreadystatechange中获取请求URL [英] XHR get request URL in onreadystatechange

查看:89
本文介绍了XHR在onreadystatechange中获取请求URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过"onreadystatechange"方法获取请求的网址?

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

我想运行多个XHR请求,并知道其中哪些会回来:

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

推荐答案

有3种简单的方法.

1:使用已描述的闭包

1: use closures as already described

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

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:将需要的数据放入回调中(我的首选解决方案)

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

这篇关于XHR在onreadystatechange中获取请求URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆