我想在网站上添加加载程序,并且我正在使用ajaxStart和ajxStop请求来隐藏和显示div。但是问题是ajaxStart和ajaxStop请求没有被按钮onclick触发。
下面是我的代码:
<style>
//css for loader
//another class with overflow=hidden
</style>
现在,我想做的是:
$("#msg1").click(function(event){ //msg1 is the id of the button
$body = $("body");
$.ajaxSetup({'global':true});
$(document).ajaxStart(function(){
$body.addClass("loading");
});
});
但这不起作用。下面的代码有效:
$("#msg1").click(function(event){ //msg1 is the id of the button
alert("Hello");
});
所以,我错过了重点吗?
最佳答案
ajaxStart
将为ajax请求开始时注册一个处理程序,它实际上不会触发ajax调用。使用您编写的内容,如果您现在使用任何jQuery方法进行ajax调用,“正在加载”类将被添加到body标签中。
例如
$( ".result" ).load( "ajax/test.html" );
更新
将您的代码更改为这样的代码以使其工作
// Move these out of the click handler as they don't have to run every time
// the button is clicked.
var $body = $("body");
$.ajaxSetup({'global':true});
$(document).ajaxStart(function(){
$body.addClass("loading");
});
$("#msg1").click(function(event){
// Here is where you actually make the ajax call, so the "loading" class
// will now be added to the body tag.
$.ajax( "example.php" )
.done(function(data) {
// Do something with the data you've just retrieved.
// You probably now want to remove the "loading" class too.
})
});
关于javascript - ajaxStart在onclick上不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42880344/