[英]Calling a function until jQuery .post finishes loading
我是jQuery框架的新手,在將AJAX與常規javascript一起使用時,我使用readyState()
函數來顯示加載的gif圖像。 但是,我不知道如何在jQuery .post()
方法中使用它。 在加載完成之前是否可以添加一個類? 如果是這樣,請提供代碼示例。 我的功能與此類似:
$.post("verify.php",{
username: u,
password: p
},function(r) {
if(r == 1) {
$(".elmt").addClass("loading");
} else if (r == 0) {
location.href = 'http://localhost';
}
});
只需在$.post()
之前調用addClass
並完成它
$(".elmt").addClass("loading");
$.post("verify.php", {
username: u,
password: p
}, function (r) {
location.href = 'http://localhost';
});
您可以在啟動AJAX請求之前觸發自定義事件。 然后在您的成功功能中,觸發另一個以停止。
或者,如果您只想要加載動畫:
$(".elmt").addClass("loading");
$.post("verify.php",{
username: u,
password: p
},function(r) {
$(".elmt").removeClass("loading");
// etc...
});
我總是喜歡將$.ajax
用於此類操作,因為它比快捷方式具有更多的選擇:
$.ajax({
type: 'POST',
url : 'verify.php',
data: {
username: u,
password: p
},
beforeSend: function () {
$(".elmt").addClass("loading"); // add loader
}
}).always(function() { // always executed
$(".elmt").removeClass("loading"); // remove loader
}).done(function(r) { // executed only if successful
if (r == 0) {
location.href = '/';
}
});
使用ajaxStart()和ajaxStop()有一種全局的方法來執行此操作。 請參閱如何在jQuery中顯示加載微調器?
如果您需要滿足所有要求。 您可以嘗試:
$(document).ajaxStart(function(){
$(".elmt").addClass("loading");
});
$(document).ajaxStop(function(){
$(".elmt").removeClass("loading");
});
但是在請求花費很少的時間時始終顯示負載並不是很酷,因為這會導致屏幕閃爍。 嘗試:
var timer;
$(document).ajaxStart(function(){
timer = setTimeout(function(){
$(".elmt").addClass("loading");
},1500);
});
$(document).ajaxStop(function(){
clearTimeout(timer);
$(".elmt").removeClass("loading");
});
通過添加計時器,應僅將耗時超過1.5秒的請求視為較長並顯示加載圖標。
如您在下面的代碼中看到的,您可以對post方法的不同結果進行處理
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.always(function(){ alert("second finished"); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.