0

私はJavaスクリプト機能を持っています

function myfunction() {

    var url = location.href;
    var ajaxRespose;

        $.ajax({
            type:"GET",
            url: url,
            cache:false,
            dataType: "text",
            success: function(response) {
                var data = $.parseJSON(response);
                ajaxRespose = data;
                console.debug("ajaxRespose ==>:"+ajaxRespose);
            }
        });
        console.debug("first ajaxRespose: " +ajaxRespose);
    }
    return false;
}

私のコンソール(firbug)で私は得る:

first ajaxRespose: undefined

ajaxRespose ==>:[object Object]

私の質問は、「最初の」console.debug の後に ajax 呼び出しが実行される理由です。PS: 関数を簡略化しました (関数は正常に動作しますが、問題は実行順序にあります)。

4

3 に答える 3

1

AJAX は非同期であるため (名前の由来)。「最初のajaxRespose」を記録するコンソールログは、AJAXリクエストが完了する前に実行されているため、未定義になります。その後、AJAX 要求が完了し、応答を取得します。

于 2013-04-02T09:21:54.007 に答える
1

$.ajax()非同期であるため、一連のイベントは次のように発生します。

$.ajax(...);   // executes AJAX request
console.debug("first ajaxResponse:" + ajaxRespose);   // undefined

/* some time later, we receive AJAX response */

// it executes the success function from the original AJAX request
console.debug("ajaxRespose ==>:"+ajaxRespose);  // [object Object]
于 2013-04-02T09:22:03.557 に答える
1
于 2013-04-02T09:24:09.257 に答える