3

javascript中的以下代码给了我错误“this.callback is not a function

function ajaxRequest()
{
    var httpObject;

    this.open = open;
    this.callback = function(){};

    function getHTTPObject()
    {
        if (window.ActiveXObject) 
            return new ActiveXObject("Microsoft.XMLHTTP");
        else if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else 
        {
            alert("Your browser does not support AJAX.");
            return null;
        }
    }

    function onstatechange()
    {
        if(httpObject.readyState == 4)
        {
            this.callback(httpObject.responseText);
        }

    }


    function open(url, callback)
    {
        httpObject = getHTTPObject();
        if (httpObject != null) 
        {
            httpObject.open("GET", url, true);
            httpObject.send(null);
            this.callback = callback;
            httpObject.onreadystatechange = onstatechange;
        }
    }
}

为什么 open 方法不将回调参数视为函数?

如果是这样,那么为什么我不能在 onstatechange 函数中调用它?

我如何使这项工作?

4

1 回答 1

11

原因是因为onstatechange被调用为事件处理程序,并且this指针可能指向触发事件的ajaxRequest对象,而不是您期望的对象。

下面的重写将变量存储在 onstatechange() 函数有权访问的执行上下文中this调用的变量中。that这应该可以解决问题。

总而言之,如果您不彻底了解 Javascript 闭包和执行上下文,即使您了解,使用框架来执行 AJAX 请求也会好得多。jQuery 和 Prototype 是不错的选择。

function ajaxRequest()
{
    var httpObject;

    this.open = open;
    this.callback = function(){};
    var that = this;

    function getHTTPObject()
    {
        if (window.ActiveXObject) 
                return new ActiveXObject("Microsoft.XMLHTTP");
        else if (window.XMLHttpRequest)
                return new XMLHttpRequest();
        else 
        {
                alert("Your browser does not support AJAX.");
                return null;
        }
    }

    function onstatechange()
    {
        if(httpObject.readyState == 4)
        {
                that.callback(httpObject.responseText);
        }

    }


    function open(url, callback)
    {
        httpObject = getHTTPObject();
        if (httpObject != null) 
        {
                httpObject.open("GET", url, true);
                httpObject.send(null);
                this.callback = callback;
                httpObject.onreadystatechange = onstatechange;
        }
    }
}
于 2009-01-19T07:28:38.217 回答