我正在寻找一种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);
}
答案 0 :(得分:1)
你可以在/完成时使用JQuery。启动您的状态指示器,然后像这样使用/完成:
// 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();
});
ajax调用完成后,done
内的代码被触发。
答案 1 :(得分: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调用之前执行。在呼叫结束后,无论AJAX是成功还是失败,Complete
都会执行。