[英]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.