jquery在多个ajax调用上显示加载器

时间:2011-09-17 16:22:24

标签: jquery ajax

我有两个字段:

  1. 用户名

  2. 电子邮件

  3. 当关注以太场时,我想在ajax调用时显示加载器 正在检查用户名或电子邮件是否已存在(取决于重点字段)

    这是我写的jquery代码:

    $().ready(function () {
        $("#Username, #Email").bind('focusout', processCheck);
    });
    
    function processCheck() {
        if ($(this).val() == '')
            return;
        $(this).next().find('img').bind('ajaxStart', loading);
        $.ajax({
            type: "POST",
            url: 'Is' + $(this).attr("id") + 'Exists',
            data: "{'" + $(this).attr("id") + "':'" + $(this).val() + "'}",
            contentType: "application/json; charset=utf-8",
            async: true,
            dataType: "json",
            success: function (msg) {
    
            }
        });
    }
    
    function loading() {
        $(this).show().unbind('ajaxStart').bind('ajaxStop', loadingStop);
    }
    
    function loadingStop() {
        $(this).hide().unbind('ajaxStop');
    }
    

    嗯,它没有按预期工作:)

    第一个焦点工作正常。然后,第二个在第一个完成之前不会触发。

    我需要这两个字段的异步工作。

    任何想法如何实现?

    先谢谢!

2 个答案:

答案 0 :(得分:2)

我不确定jquery是否注册了ajaxStart和ajaxStop自定义 在dom中的事件,但无论如何,$ .ajaxStart()和$ .ajaxStop()不 真的那样工作。它们就像事件代码“包装器”。我可以 为您提供这两个功能的解决方案,但您不需要 它们。

function processCheck() {
    var $this = $(this);
    if ( $this.val() == '' ) return;
    $img = $this.next().find('img');
    $img.show();
    $.ajax({
        type: "POST",
        url: 'Is' + $this.attr("id") + 'Exists',
        data: "{'" + $this.attr("id") + "':'" + $this.val() + "'}",
        contentType: "application/json; charset=utf-8",
        async: true,
        dataType: "json",
        success: function (msg) {
            // stuff
            $img.hide();
        }
    }).always(function () { 
        $img.hide(); 
    });
}

答案 1 :(得分:0)

$('#loadingDiv').hide()  // hide it initially
      .ajaxStart(function () {
        //alert('started');

        $('#loadingDiv').show();
       })
      .ajaxStop(function () {
       //alert('stoped');

        $('#loadingDiv').hide();
    });

<span id="loadingDiv"><img src="images/ajax-loader.gif" alt="Loading..."></span>