javascript - ajaxStart 不适用于 onclick

标签 javascript jquery ajax

我想在我的网站中添加加载程序,并且我正在使用 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 调用,“loading”类将被添加到 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/

相关文章:

PHP 在 ajax 中从不返回 readState 4 或 status 200

c# - C# 和 JavaScript 之间的 pbkdf2 计算不一致

javascript - OpenWeatherMap API - 附加经度和纬度时出现问题

jquery - 有没有更好的方法来检查 AJAX 请求的值是否有效?

JQuery 更新选择下拉列表中的文本

javascript - 您如何在两个浏览器选项卡/窗口之间进行通信?

javascript - 在现有 AJAX 调用出现错误的情况下进行另一个 Jquery AJAX 调用

javascript - PHP 将 JSON 对象返回给 Javascript [AJAX CALL] 不起作用

javascript - 表单验证条件与 react

javascript - DocuSign 自定义按钮问题,帐户名称包含撇号和/或 & 符号