-3

私は奇妙なJavascriptの振る舞いに遭遇しています:

index.html

<div id="content">
    <button type="button" onclick="goDownload()">Click</button>
</div>

hello.html

<div id="myId">
</div>

<script type="text/javascript">
    $(function() {
        doStuff();
    });
</script>

file.js

function goDownload() {
    $.ajax({
        url: "hello.html",
        cache: false,
        success: function (response) {
            $("#content").append(response);
        }
    });        
}

function doStuff() {
    //If I wait a little bit (e.g alert/timer), the below works
    //otherwise it does not

    $("#myId").html("Hello from doStuff()");
}

ajax呼び出しが非同期リクエストであることは知っていますが、これがどの時点で問題になっているのかわかりません。(成功コールバックでdoStuff()を実行できることはわかっていますが、これは私には当てはまりません)。何か案は?

4

1 に答える 1

1

呼び出しの結果は$.ajaxDeferredオブジェクト(http://api.jquery.com/category/deferred-object/)であるため、そのメソッドを利用して、実行が完了したことを検出できます。

var downloadWaiting;

function goDownload() {
    downloadWaiting = $.ajax({
        url: "hello.html",
        cache: false,
        success: function (response) {
            $("#content").append(response);
        }
    });
}

function doStuff() {
    downloadWaiting.done(function () {
        $("#myId").html("Hello from doStuff()");
    });
}
于 2013-02-05T20:41:15.137 に答える