如何在Ajax中获取数据时加载图像微调器

时间:2012-11-16 12:57:22

标签: ajax

我从这个网站得到了很好的回应。现在我的最后一件事是在Ajax中获取数据时显示gif加载图像。

我的代码是:

function vote(id)
{ 

    var result = new Array();
    document.getElementById('sub-cat').innerHTML = ajax_image; 
     result = $.ajax({
                       type: "POST",
                       url: "ajax.php",
                       data: "id="+id,
                       async: false
               }).responseText.split("^");
document.getElementById('sub-cat').innerHTML = result[0];
document.getElementById('sub-cat1').innerHTML = result[1];


//window.location.reload()
}

我尝试了以下代码,但没有工作...... :(

function vote(id)
{ 
    var ajax_image = "<img src='_assets/images/tire-loader.gif' alt='Loading...' />";

    var result = new Array();
     //$('#sub-cat').html(ajax_image);
    document.getElementById('sub-cat').innerHTML = ajax_image; 
     result = $.ajax({
                       type: "POST",
                       url: "ajax.php",
                       data: "id="+id,
                       async: false
               }).responseText.split("^");
document.getElementById('sub-cat').innerHTML = result[0];
document.getElementById('sub-cat1').innerHTML = result[1];


//window.location.reload()
}

非常感谢您的辛勤工作

1 个答案:

答案 0 :(得分:1)

There are some callbacks in ajax request, beforeSend,success,complete,error etc... So you just have you show the image in beforeSend callback and hide it in complete callback.
$.ajax({
       type: "POST",
       url: "ajax.php",
       data: "id="+id,
       async: false,
       beforeSend: function(){
         document.getElementById('sub-cat').innerHTML = ajax_image;
       },
       complete: function(){
         document.getElementById('sub-cat').innerHTML = "";
       }
          }).responseText.split("^");
    document.getElementById('sub-cat').innerHTML = result[0];
    document.getElementById('sub-cat1').innerHTML = result[1];

    });