2013-05-17 100 views
6

我在我的网站上使用jQuery与jQuery,需要显示进度/加载指标。同步Ajax加载指标

我的dilemna是这样的:

  • 同步AJAX锁定浏览器,所以我不能做任何事情(如显示加载指示器),直到内容被返回,而此时为时已晚
  • 我使用JSON作为返回数据类型正在和设置异步= true,则返回一个空应答串
  • 我的整个框架依赖于返回类型被JSON格式

我似乎无法找到任何方法让JS向用户指示某事正在进行中,除了做一个alert()。 (出于某种原因,警报确实有效)。

有什么建议吗?

我的代码:

JS

var jqXHR = $.ajax(
{ 
    type: "POST", 
    url: url, 
cache: false, 
    data: params, // array of parameters 
    async: false, // responseText is empty if set to true 
    dataType: 'json', 
    error: function() 
    { 
     alert("Ajax post request to the following script failed: " + url); 
    } 

}); 

var html = jqXHR.responseText; 

PHP

$return = array(); 
$return['status'] = 1; 
$return['message'] = "some html here ..."; 
echo json_encode($return); 

回答

12

您需要调用Ajax请求 之前显示加载显示,您可以使用回调函数和success到隐藏加载显示器

//show here the loading display 
    $(".loading").show(); 
    setTimeout(function() { 
    var jqXHR = $.ajax({ 
     type: "POST", 
     url: url, 
     cache: false, 
     data: params, // array of parameters 
     async: false, // responseText is empty if set to true 
     dataType: 'json', 
     error: function(){ 
       alert("Ajax post request to the following script failed: " + url); 
     }, 
     success: function(){ 
       //hide loading display here 
       $(".loading").hide(); 
     } 
    }); 
    }, 0); 

你需要在调用ajax函数之前使用setTimeout()延迟,因为它甚至可以暂停加载显示的显示,因为在$(".loading").show();被动画时,同步ajax请求将被调用,并且在加载之前肯定会锁定浏览器显示动画将完成

+0

感谢您的建议。我试过这个,但是当其他代码似乎运行时,我得到一个空的响应文本,尝试从尚未运行的ajax函数获取响应文本,并失败。不幸的是,在所有其他代码上设置TimeTime并不实际,因为抓取responseText的代码遍及整个系统...... –

+1

好吧,我最终使用了超时并修补了我的所有代码,并且它工作得很好。所以感谢给我一个刺激让我在那里(会投你,但没有足够的声望点!) –

+0

谢谢!它的工作原理... – maverabil

9

您可以使用JQuery全局Ajax事件处理程序。此链接介绍详细介绍它们:

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

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

$(document).ajaxComplete(function() { 
    $("#loading").hide(); 
}); 
+0

感谢您的建议。不会悲伤地工作,看来只有在函数完成时才会应用DOM更改(到时候已经太晚了......) –

+0

代码中的第一个函数可能是$(document).ajaxSend(function(){... ' – Gh61

2

嗨使用像一些事情得到在Magento后....

这是HTML

<div class="popupNews"> 
    <div class="popClose">X</div> 
     <div id="loading"><img src="<?php echo $this->getSkinUrl('images/loader.gif'); ?>" border="0" /></div> 
     <div id="result"></div> 
    </div> 
</div> 

而这个jquery

var url = 'http://blabla.com/ajax'; 

jQuery.ajaxSetup({ 
    beforeSend:function(){ 
     jQuery("#loading").show(); 
    }, 
    complete:function(){ 
     jQuery("#loading").hide(); 
    } 
}); 

jQuery.ajax({ 
    url: url, 
    type: 'POST', 
    data: {id: post}, 
    success: function(data) { 
     jQuery("#result").html(data); 
    } 
});