0

我有一个非常简单的 javascript 类,它通过 jquery 对我的 Web 服务进行 ajax 调用。它成功返回数据,但我无法通过我设置数据的变量来检索它。我认为这不是 ajax 调用是否异步的问题,因为我已经为所有 ajax 事件设置了事件处理程序,但其中一些不会触发。我不知道出了什么问题。这是完整的代码:

Javascript:

function testClass(){
    this.returnData = "";
    this.FireAjax = function(){
        $.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?",
            function(data){
                this.returnData = data.d;
                alert(data.d);
            }
        );  
    }

}

HTML页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://localhost/mywebapp/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="testClass.js"></script>

<script type="text/javascript">
    $(document).ready(function(){

        var obj = new testClass();

        $("#debug").ajaxError(function(event, request, settings){
            $(this).append("<b>Ajax Error!</b><br />"); //this does not fire
        });

        $("#debug").ajaxSend(function(evt, request, settings){
            $(this).append("<b>Ajax Send!</b><br />"); //this does not fire!?
        });

        $("#debug").ajaxStop(function(){
            $(this).append("<b>Ajax Stopped</b><br />"); //this fires
        });

        $("#debug").ajaxComplete(function(event,request, settings){
            $(this).append("<b>Ajax Completed!</b><br />"); //this fires
            $(this).append("<h2>" + obj.returnData + "</h2>"); //this returns an empty string!!!!!!
        });

        $("#debug").ajaxSuccess(function(evt, request, settings){
            $(this).append("<b>Ajax Successful!</b><br />"); //this fires
        });

        $("#debug").ajaxStart(function(){
            $(this).append("<b>Ajax Started!</b><br />"); //this fires
        });

        obj.FireAjax();
    });
</script>
</head>

<body>
<div id="debug">

</div>
</body>
</html>

附加信息: 如果我在我的 html 页面中删除了 complete 事件并将对 obj.returnData 的调用放在我的 stop 事件中(认为我的 html 完成事件可能会覆盖我的 testClass 完成函数),我会得到相同的结果。

4

1 回答 1

1

你的问题在这里:

this.returnData = data.d;

this匿名函数内部是指 jQuery Options 对象,而不是对象的实例。

试试这个:

function testClass(){
    this.returnData = "";
    var that = this;
    this.FireAjax = function(){
        $.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?",
                function(data){
                        that.returnData = data.d;
                        alert(data.d);
                }
        );      
    }

}
于 2009-08-14T19:58:56.347 回答