0

ajax リクエストの実行中に何らかのステータスを表示する JavaScript ソリューションを探しています。試してみdocument.getElementById("status").innerHTML = "<h2>Loading....</h2>";ましたが、うまくいきませんでした。何か案は?

function codesDelete(id) {
    var ajax;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }

    ajax.onreadystatechange = function() {
        if (ajax.readyState === 4 && ajax.status === 200) {
            document.getElementById("status").innerHTML = "<h2>Data Deleted!</h2>";
        }
    }

    // this is what i tried
    document.getElementById("status").innerHTML = "<h2>Loading....</h2>";


    ajax.open("GET", "code.php?id=" + id, true);
    ajax.send();

    setTimeout(function() {
        document.getElementById("status").style.display = "none";
    }, 3000);
}
4

2 に答える 2

1

JQuery の when/done を使用できます。ステータス インジケーターを開始し、次のように when/done を使用します。

// start the status indicator wherever it's appropriate    
StartStatusIndicator();

//Make your ajax call
$.when($.ajax({
    type: "POST",
    ...more stuff...
    success: function (json) {
        ...even more stuff...
    }
})).done(function () {
    KillYourStatusIndicator();
});

doneajax 呼び出しが終了すると、内部のコードが起動されます。

于 2012-09-18T21:14:39.553 に答える
1

あなたができる別の方法は、次のように、jQuery.ajax でbeforeSendおよびコールバックを使用することです。complete

$.ajax({
    beforeSend:function(){
        // Create and insert your loading message here as you desire
        // For example, a version of what you were trying to do would be:
        $("#status").html("<h2>Loading....</h2>");
    },
    // ... whatever other things you need, such as a success callback, data, url, etc
    complete: function(){
       // Remove your loading message here, for example:
       $("#status").html("");
    }
});

名前beforeSendが示すように、AJAX 呼び出しが行われる前に実行されます。Complete呼び出しが終了した後、AJAX が成功したか失敗したかに関係なく実行されます。

于 2012-09-18T21:26:00.917 に答える