0

我正在寻找一种 JavaScript 解决方案,以在发生 ajax 请求时显示某种状态。我试过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 像这样:

// 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();
});

done当 ajax 调用完成时,里面的代码会被触发。

于 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 回答