在XMLHttpRequest.onload中获取HTTP方法

时间:2017-03-05 00:45:26

标签: javascript xmlhttprequest

假设我在全球范围内有XMLHttpRequest的实例 另外,我有两个不相交的范围“A”和“B”。

请求实例request在全球范围内可用 然后,在范围“A”内定义HTTP方法method 之后,发送请求并在范围“B”内处理其onload事件。

因此,变量method在“A”中定义,我无法从“B”访问它。
有没有办法只使用request实例找到范围“B”中的HTTP方法?

/* Global scope starts */

var request = new XMLHttpRequest();

/* Scope A starts */

var method = 'POST', // or 'GET' - chosen HTTP-method
    url = '/some/url';

request.open( method, url, true );

/* 
 * Scope A ends
 *
 * [then some code]
 *
 * Scope B starts
 */

request.send();

request.onload = function() {
    /* 
     * Is there any way 
     * to find out HTTP-method here?
     */
}

/* Scope B ends */

/* Global scope ends */

1 个答案:

答案 0 :(得分:2)

你可以像这样使用XMLHttpRequest.prototype.open方法修补

XMLHttpRequest.prototype.open = (function(original) {
    // in case this code is called twice
    if (original.name === 'newOpen') {
        return original;
    }
    return function newOpen(method, url, asyncflag, user, password) {
        this.xopen = { method: method, url: url, asyncflag: asyncflag, user: user, password: password };
        return original.apply(this, arguments);
    }
})(XMLHttpRequest.prototype.open);

然后

request.onload = function() {
    console.log(this.xopen.method); // the method used is output
}