首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

ajax封装有关问题,请

2013-04-07 
ajax封装问题,请高手指点看下面红色代码中的this.bind怎么定义,现在这里的this是代表 var xm new XMLHtt

ajax封装问题,请高手指点
看下面红色代码中的this.bind怎么定义,现在这里的this是代表 var xm = new XMLHttpRequest();中的xm,但是我现在想得到this.bind(this, function () {}中蓝色字中的this是实例AjaxRequest的对象引用,比如:var aa=new AjaxRequest(method, url, data, callback);我想蓝色的this是aa这个实例后的对象。但是不知道怎么搞。
function AjaxRequest(method, url, data, callback) {
    this.method = method;
    this.url = url;
    this.data = data;
    this.callback = callback;
    this.send = function () {
        var xm = new XMLHttpRequest();
        this.url = (data.length > 0 && this.method == "get") ? this.url + "?" + this.data : this.url;
        xm.open(this.method, this.url, true);
        if (this.method == "get") {
            xm.setRequestHeader("If-Modified-Since", 0);
        } else {
            xm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        xm.onreadystatechange = this.bind(this, function () {
            if (xm.readyState == 4 && xm.status == 200)
                this.callback(xm.responseText);
        });
        if (this.method == "get") {
            xm.send();
        }
        else {
            xm.send(this.data);
        }
    }
}
[解决办法]
作用域问题
var _this = this;
this.send = function () {
        var xm = new XMLHttpRequest();
        _this.url = (data.length > 0 && this.method == "get") ? _this.url + "?" + _this.data : _this.url;
       ...
    }
send函数里面所有this改为_this就行了
[解决办法]


引用:
作用域问题
var _this = this;
this.send = function () {
        var xm = new XMLHttpRequest();
        _this.url = (data.length > 0 && this.method == "get") ? _this.url + "?" + _thi……

 更正一下


    var _this = this;
    xm.onreadystatechange = function () {
            if (xm.readyState == 4 && xm.status == 200)
                _this.callback(xm.responseText);
        };
这样才行

热点排行