How do I load an image while waiting for AJAX response?

前端 未结 1 1743
悲&欢浪女
悲&欢浪女 2021-01-31 19:52

I was wondering if I could get some pointers. I am trying to use a loading gif while getting a response from an ajax request. The issue I am running into is that it will not dis

相关标签:
1条回答
  • 2021-01-31 20:39

    Actually you need to do this by listening ajaxStart and Stop events and binding it to the 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>

    0 讨论(0)
提交回复
热议问题