Jquery Ajax正在加载图像

Ker*_*ott 36 ajax jquery

我想为我的jquery ajax代码实现一个加载图像(这是jquery仍在处理的时候)下面是我的代码:

$.ajax({
    type: "GET",
    url: surl,
    dataType: "jsonp",
    cache : false,
    jsonp : "onJSONPLoad",
    jsonpCallback: "newarticlescallback",
    crossDomain: "true",
    success: function(response) {
        alert("Success");
    },
    error: function (xhr, status) { 
        alert('Unknown error ' + status);
    }   
});
Run Code Online (Sandbox Code Playgroud)

如何在此代码中实现加载图像.谢谢

KMa*_*Man 53

尝试这样的事情:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 你能加点缩进吗?这会使血液从我的眼睛里流出来:P (10认同)
  • 而不是用代码$.("#LoadingImage")重复你的自我.hide(); 在"成功"和"错误"功能中,使用Ajax选项的"完整"功能. (8认同)

dkn*_*ack 52

描述

你应该用jQuery.ajaxStart和做jQuery.ajaxStop.

  1. 用你的形象创建一个div
  2. 让它可见 jQuery.ajaxStart
  3. 隐藏它 jQuery.ajaxStop

样品

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>
Run Code Online (Sandbox Code Playgroud)

更多信息

  • 因此,使用此方法,将显示每个ajax请求图像.如果我不想怎么办?如果要在不通知用户的情况下静默执行某些ajax请求. (2认同)
  • @svlada,您可以为某些ajax请求禁用ajax全局事件,只需在此ajax请求选项中将global设置为false. (2认同)