在等待AJAX​​响应时加载gif

Chr*_*ris 15 ajax jquery

我想知道我是否能得到一些指示.我试图在从ajax请求获得响应时使用加载gif.我遇到的问题是它在发送电子邮件时不会显示gif.

我在这里查看了几个页面试图找到解决方案,但它们似乎都没有工作.这是我看过的网页:而jQuery的AJAX运行加载GIF图像显示加载图片,同时用后阿贾克斯执行,而$就显示加载图片

我使用以下代码来尝试实现此目的:

$("#loading").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxStop", function(){
$(this).hide();
});
Run Code Online (Sandbox Code Playgroud)

这没有显示gif,我也尝试了以下内容:

$.ajax({
 type: "POST",
 url: "contact1.php",
 data: dataString,
 beforeSend: loadStart,
 complete: loadStop,
 success: function() {
  $('#form').html("<div id='msg'></div>");
  $('#msg').html("Thank you for your email. I will respond within 24 hours. Please reload the page to send another email.")
 },
 error: function() {
  $('#form').html("<div id='msg'></div>");
  $('#msg').html("Please accept my apologies. I've been unable to send your email. Reload the page to try again.")
 }
}); 
return false;
});
function loadStart() {
  $('#loading').show();
}
function loadStop() {
  $('#loading').hide();
}
Run Code Online (Sandbox Code Playgroud)

我还尝试在ajax请求之前放置$("#loading").show()并在成功和错误函数中放置.hide().我仍然没有得到任何表现.

提前致谢

pal*_*aѕн 33

实际上你需要通过监听ajaxStart和Stop事件并将它绑定到document:

$(document).ready(function () {
    $(document).ajaxStart(function () {
        $("#loading").show();
    }).ajaxStop(function () {
        $("#loading").hide();
    });
});
Run Code Online (Sandbox Code Playgroud)

$(document).ajaxStart(function() {
  $("#loading").show();
}).ajaxStop(function() {
  $("#loading").hide();
});

$('.btn').click(function() {
  $('.text').text('');
  $.ajax({
    type: "GET",
    dataType: 'jsonp',
    url: "https://api.meetup.com/2/cities",
    success: function(data) {
      $('.text').text('Meetups found: ' + data.results.length);
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
#loading { display: none; }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me!</button>
<p class="text"></p>
<div id="loading">
  <!-- You can add gif image here 
  for this demo we are just using text -->
  Loading...
</div>
Run Code Online (Sandbox Code Playgroud)