0

私はjqueryを介して私のWebサービスへのajax呼び出しを行う非常に単純なjavascriptクラスを持っています。データは正常に返されますが、データを設定した変数を介してデータを取得できません。すべての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イベントを削除し、stopイベントでobj.returnDataを呼び出すと(おそらくhtmlcompleteイベントがtestClasscomplete関数を上書きすると考えて)、同じ結果が得られます。

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 に答える