用ajax请求加载GIF


loading gif with ajax request

 $(".content-short").click(function() {
      var ID = $(this).attr('data-id');
      $('.loadingmessage').show(); 
      $.ajax({   
          type: "post",
          url: "collegeselect.php",
          data: 'ID=' + ID,
          dataType: "text",                  
          success: function(response){                    
              $(".content-full").html(response); 
              $('.loadingmessage').hide(); 
          }
      });
    });

//collegeselect.php//用于从数据库加载数据,//。Loadingmessage//for gif

当我第一次使用它时,它显示gif,但是gif在第一次点击后不显示,因为检索到的数据已经可以从以前的ajax请求中获得完整的内容。如何显示它在每次点击内容短类?

发生这种情况是因为您正在将实际内容替换为加载GIF图像的响应。

因此,当您第一次单击它时,在ajax调用成功后,按照代码显示,您已经替换了.content-full的内容,并且没有可用的GIF。

解决方案: 要解决要么发送相同的图像标签与响应或移动加载器图像的.content-full

在请求成功前添加beforeSend : function()

$(".content-short").live(function() {
      var ID = $(this).attr('data-id');
      $('.loadingmessage').show(); 
      $.ajax({   
          type: "post",
          url: "collegeselect.php",
          data: 'ID=' + ID,
          dataType: "text",
          beforeSend : function()
          {
            $('.loadingmessage').show();
          },
          success: function(response){                    
              $(".content-full").html(response); 
              $('.loadingmessage').hide(); 
          }
      });
    });

从评论中,我收集到img.content-full容器内。问题是,当ajax成功时,img被删除,因为您正在执行$(".content-full").html()。修复它的一种方法是将img移出容器。另一种方法是存储对img的引用,并通过.append().prepend()将其与响应一起添加,如下所示。

$(".content-short").click(function() {
    var ID = $(this).attr('data-id');
    $('.loadingmessage').show();
    $.ajax({
        type: "post",
        url: "collegeselect.php",
        data: 'ID=' + ID,
        dataType: "text",                  
        success: function(response) {
            var $content = $(".content-full");
            var $loaderImg = $content.find('.loadingmessage').hide();
            $content.html(response).prepend($loaderImg);
        }
    });
});

下面是一个通过setTimeout模拟行为的演示。