在发出AJAX请求时使用jQuery显示加载栏

gur*_*gui 5 ajax jquery

我正在用jquery做一个AJAX请求:

$.get('/Stuff.php', function (data) {
    $('#own').html(data);
});
Run Code Online (Sandbox Code Playgroud)

当这个数据加载时,我想在页面顶部显示一个小文本(只是说"正在加载..."),而不会阻止它.

这该怎么做?

Raf*_*fay 8

使用ajaxSetup

$.ajaxSetup({
    beforeSend:function(xmlHttpRequest){
    //show the loading div here
    },
    complete:function(){

    //remove the div here
    }
    });
Run Code Online (Sandbox Code Playgroud)

现在进行ajax调用

$.get('/Stuff.php', function (data) {
    $('#own').html(data);
});
Run Code Online (Sandbox Code Playgroud)


Had*_*das 6

$("#loading").show();   //before send
$.get('/Stuff.php', function (data) {
    $('#own').html(data);
    $("#loading").hide();  //when sucess
});
Run Code Online (Sandbox Code Playgroud)


grr*_*grr 5

3nigma是正确的轨道,但至少在一般情况下,有一个细节是错误的.

使用ajaxSetup只提供默认值,如果以后你做了一些ajax调用,指定自己的beforeSend回调(即你需要设置一些特定的头文件)或者完成(你想要同时处理成功和错误),他们将覆盖那些ajaxSetup和你的加载指标会破裂.

相反,使用全局Ajax事件(更多关于ajax事件)

$(document).ajaxSend(function(e, jqXHR){
  //show the loading div here
});
$(document).ajaxComplete(function(e, jqXHR){
  //remove the div here
});
Run Code Online (Sandbox Code Playgroud)

这是一个更通用的解决方案,即使其他代码也想要设置一些全局或本地的beforeSend/complete处理程序或调用ajaxSetup,它也不会破坏.