使用ajax发布时显示加载图像

29 ajax jquery loading

我知道互联网上有成千上万的例子,但我想要的是我已经拥有的脚本,在检索数据时显示加载的gif图像.我的java知识很差,因此我问如何更改以下内容:

<script type="text/javascript"> 
 $(document).ready(function(){
  function getData(p){
    var page=p;
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
        }
    });
}
getData(1);

$(".page").live("click", function(){
    var id = $(this).attr("class");
    getData(id.substr(8));
        });
      });
  </script> 
Run Code Online (Sandbox Code Playgroud)

我的div在这里:

    <div class="content" id="data"></div>
Run Code Online (Sandbox Code Playgroud)

谢谢.约翰

Kel*_*tex 61

假设您在页面上的某个位置有一个标记,其中包含您的加载消息:

<div id='loadingmessage' style='display:none'>
  <img src='loadinggraphic.gif'/>
</div>
Run Code Online (Sandbox Code Playgroud)

您可以在ajax调用中添加两行:

function getData(p){
    var page=p;
    $('#loadingmessage').show();  // show the loading message.
    $.ajax({
        url: "loadData.php?id=<? echo $id; ?>",
        type: "POST",
        cache: false,
        data: "&page="+ page,
        success : function(html){
            $(".content").html(html);
            $('#loadingmessage').hide(); // hide the loading message
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 如果Ajax请求不成功,则在这种情况下加载gif仍然可见. (5认同)

小智 9

$.ajax(
{
    type: 'post',
    url: 'mail.php',
    data: form.serialize(),
    beforeSend: function()
    {
        $('.content').html('loading...');
    },
    success: function(data)
    {
        $('.content').html(data);
    },
    error: function()
    {
        $('.content').html('error');
    }
});
Run Code Online (Sandbox Code Playgroud)

玩得很开心!

如果您应该有快速加载时间,以防止显示加载,您可以添加某种超时.