接收到AJAX结果后,加载程序不会消失

时间:2015-09-09 06:59:14

标签: javascript jquery ajax loader

我有通过AJAX显示数据的页面,直到获取结果的时间我希望显示一个加载器,一旦获取结果,我希望加载器应该消失。下面是我试图显示加载程序的代码的一部分

var onSubmit = function(e) 
    {
        var txtbox = $('#txt').val();
        var hiddenTxt = $('#hidden').val();

        $("#walkaway").hide();
        $("#submitamt").hide();
        $("#xtrabutton").hide();

        LodingAnimate();
        $.ajax(
            {
                type: 'post',
                url: 'test2.php',
                dataType: 'json',   
                data: {txt: txtbox,hidden: hiddenTxt},
                cache: false,
                success: function(returndata) 
                    {
                        $('#first').html(returndata[0]);
                        $('#second').html(returndata[0]);
                        $('#third').html(returndata[0]);
                    },
                error: function() 
                    { 
                        console.error('Failed to process ajax !');
                    }
            });

            function LodingAnimate() 
            {
                $("#maillist").html('<img src="img/ajax-loader.gif" /> Please Wait Loading...');
            }   
    }; 

点击一个按钮,执行上面的AJAX,点击加载程序运行后,即使我收到回复(在控制台中),加载程序仍在运行,但实际上它应该已经消失。

1 个答案:

答案 0 :(得分:3)

你应该在ajax调用完成后手动隐藏/删除加载器,添加Jquery Complete回调并添加代码以删除其中的加载器。

Jquery Complete - 此回调将在成功执行并执行错误回调后执行。

     $.ajax(
            {
                type: 'post',
                url: 'test2.php',
                dataType: 'json',   
                data: {txt: txtbox,hidden: hiddenTxt},
                cache: false,
                success: function(returndata) 
                    {
                      //Success code
                    },
                error: function() 
                    { 
                        //error code
                    },
                complete:function()
                    {
                     //This block will execute after success/error executes.
                     //Make the loader div empty
                     $("#maillist").empty();
                    }
            });