在同步Ajax上加载指示符
我在我的网站上使用ajax和jQuery,需要显示进度/加载指示器。
我的困境是这样的:
- 同步AJAX锁定浏览器,所以我不能做任何事情(例如显示加载指示器)直到内容被返回,到那时为时已晚
- 我使用JSON作为返回数据类型,并设置async = 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);
您需要在调用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请求将被调用,并且肯定会在加载显示动画完成之前锁定浏览器
您可以使用Jquery Global Ajax事件处理程序。 此链接详细描述了它们:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
$(document).ajaxStart(function () { $("#loading").show(); }); $(document).ajaxComplete(function () { $("#loading").hide(); });
嗨使用这样的东西来获得magento的post….
这是html
X
而这就是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); } });