【问题标题】:how to show loading image while ajax function in process?如何在 ajax 函数处理过程中显示加载图像?
【发布时间】:2012-12-04 05:35:59
【问题描述】:

以下是我的 ajax 函数,它将在按钮单击时填充 html div。现在我想要的是如何在此函数启动时显示加载器图像,并且在此函数执行后加载器将隐藏。

function campaignList(){
        $.ajax({
            type:'post',
            url:'<%=campaignListURL.toString()%>',
            data:{},
            success:function(data){
                $(".main_content").html(data);                              
            }
        });
    }

我曾尝试使用以下脚本

<script type="text/javascript">
$("#loading_layer").ajaxStart(function(){
       $(this).show();
     });
</script>

但是什么都没有发生.. 以下是我想要隐藏和显示的 ajax 加载程序 gif 图像的 div

<div id="loading_layer" style="display: none">

/////////////////////////////////////// /////////////////////////// 以上是我问的 ajx 方法..但是如果我想在提交表单时做同样的事情,那么我该如何实现这个..?

以下是我提交表单的一个 javascript 代码行

{一些用于表单验证的javascript代码,如果所有验证都为真,那么标志将为真.....

   if (flag == true) {
    div.style.display = '';
 alert("");
    document.editadform.submit();
    }
         div.style.display = 'none';
        return flag;

}

以下是我的一个 div,我想在提交表单时显示隐藏的 img,完成后我想隐藏

" />

那么任何人都可以指导我解决这个问题吗?

【问题讨论】:

  • 你认为$.ajax 会如何知道ajaxStart
  • 我刚刚在某处读到,每当即将发送 Ajax 请求时,jQuery 都会检查是否还有其他未完成的 Ajax 请求。如果没有进行中,jQuery 会触发 ajaxStart 事件。使用 .ajaxStart() 方法注册的所有处理程序都在处执行

标签: jquery ajax progress-bar


【解决方案1】:

您可以在 AJAX 脚本中添加 beforeSend

查看 jquery Ajax 文档,http://api.jquery.com/jQuery.ajax/

function campaignList(){
        $.ajax({
            type:'post',
            url:'<%=campaignListURL.toString()%>',
            data:{},
            beforeSend: function ( xhr ) {
               //Add your image loader here
            },
            success:function(data){
                $(".main_content").html(data);                              
            }
        });       

 }

【讨论】:

    【解决方案2】:

    这应该可以正常工作:

    function campaignList(){
            $(".main_content").html("<img src='loader.png'>"); // show the ajax loader
            $.ajax({
                type:'post',
                url:'<%=campaignListURL.toString()%>',
                data:{},
                success:function(data){
                    $(".main_content").html(data);  // this will hide the loader and replace it with the data                            
                }
            });
        }
    

    【讨论】:

    • thnx 它非常简单,您可以指导我..我理解//但我的问题是我如何相对提供 img 源..我正在使用 liferay 我对 jquery 没有任何广泛的了解,但我的 src会像这样“request.getcontextpath”/img/loader.png“那么我怎么能把这种方式放在img的src中?
    • 好吧,您可以这样做的一种方法是创建一个全局变量,该变量将在开头保存“request.getcontextpath”/img/loader.png 的值,然后将其添加到 $( ".main_content") 对象
    • 我做到了..thanx...现在发生的事情是..图像只是一目了然..几乎没有一毫秒..有什么办法让它正确显示吗?
    • 我猜请求会在一毫秒内完成,所以它隐藏了。
    • 好的。顺便说一句thanx这个...一个简单的,在几秒钟内你解决了我的问题
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2014-09-27
    相关资源
    最近更新 更多