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

时间:2013-06-02 09:49:41

标签: jquery ajax

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

我已经在这里查看了几个页面以尝试找到解决方案,但它们似乎都没有工作。这些是我查看过的网页:Loading gif image while jQuery ajax is runningDisplay loading image while post with ajax以及Show loading image while $.ajax is performed

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

$("#loading").bind("ajaxStart", function(){
$(this).show();
}).bind("ajaxStop", function(){
$(this).hide();
});

这没有显示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();
}

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

提前致谢

1 个答案:

答案 0 :(得分:32)

实际上你需要通过监听ajaxStart和Stop事件并将其绑定到document来实现这一点:

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

$(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);
    }
  });
});
#loading { display: none; }
<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>