【问题标题】:What is AJAX option that handle request while it's not complete?什么是在请求未完成时处理请求的 AJAX 选项?
【发布时间】:2016-01-16 18:14:14
【问题描述】:

我想在 AJAX 请求未完成处理且尚未从服务器返回时显示加载图像,是否有任何选项可以在状态未完成时处理 ajax

 jQuery.ajax({
            url: "/privileges/users/get-group-users",
            type: "POST",
            dataType: 'JSON',
            data: {
                "group_id":groupId
            },
            success: function(users){

            },
            error: function(e){

            }
        });

有没有成功或错误之类的选项???

【问题讨论】:

标签: jquery ajax


【解决方案1】:

使用ajaxStart - ajaxStop

<img src="img/loading.gif" style="display:none;" id="loading"/>

JS:

// if there is any ajax call the loading image will be visible
$("#loading").ajaxStart(function(){
   $(this).show();
 });

//if the ajax call stoped hide the loading image
$("#loading").ajaxStop(function(){
   $(this).hide();
 });

【讨论】:

  • 我可以在 ajaxStart 回调函数中获取请求的 url 吗?我想防止某些 Ajax 调用出现加载图像。
【解决方案2】:

只要您使用异步 AJAX 请求,它就会在您调用$.ajax() 时隐式进行,并在调用successerror 函数时完成。

使用现代 jQuery(即 1.5+)时更好的模型是这样的:

var jqXHR = $.ajax({ ... });    // don't put success and error in yet

var $splash = $(...).show();

jqXHR.always(function() {
    $splash.hide();
}).done(function(users) {
    ...
}).fail(function(e) {
    ...;
});

【讨论】:

    【解决方案3】:

    你可以使用:

    $('#loading').ajaxStart(function() {
      $(this).show();
    }).ajaxComplete(function() {
      $(this).hide();
    });
    

    【讨论】:

      【解决方案4】:

      这里是$.ajax()提供的回调钩子:

      beforeSend 回调被调用;它接收 jqXHR 对象和设置映射作为参数。

      error 如果请求失败,将按照注册顺序调用回调。他们接收 jqXHR、一个指示错误类型的字符串和一个异常对象(如果适用)。一些内置错误会提供一个字符串作为异常对象:“abort”、“timeout”、“No Transport”。

      dataFilter 成功接收响应数据后立即调用回调。它接收返回的数据和 dataType 的值,并且必须返回(可能更改的)数据才能传递成功。

      success 如果请求成功,则按照注册顺序调用回调。它们接收返回的数据、包含成功代码的字符串和 jqXHR 对象。

      complete 回调触发,按照它们注册的顺序,当请求完成时,无论是失败还是成功。它们接收 jqXHR 对象,以及包含成功或错误代码的字符串。

      来源:jQuery API

      关于 $.ajax() 的所有细节都非常详细地给出了

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        相关资源
        最近更新 更多