同步Ajax加载指示器

9
我在我的网站上使用jQuery的ajax功能,需要显示一个进度/加载指示器。
我的困境是:
1. 同步AJAX锁定了浏览器,所以我无法做任何事情(例如显示加载指示器),直到内容返回,那时为时已晚。
2. 我正在使用JSON作为返回数据类型,并且设置async = true会返回一个空响应字符串。
3. 我的整个框架依赖于返回类型为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);
3个回答

20

在调用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()来延迟一段时间,因为同步的ajax请求会在加载动画完成之前锁定浏览器,导致加载动画无法正常显示。


谢谢您的建议。我尝试了这个方法,但是我得到了一个空响应文本,因为代码的其余部分似乎在运行中,试图从尚未运行的ajax函数中获取响应文本,而且失败了。不幸的是,在我的其他代码上设置setTimeout并不现实,因为获取responseText的代码遍布整个系统... - little_edian
2
好的,最终我使用了超时并修补了所有代码,现在它运行得很好。所以感谢你给了我推动力(想为你投票,但是没有足够的声望点数!) - little_edian
我认为设置超时将使 AJAX 调用变成异步的。 - Pankaj Agrawal

10

谢谢您的建议。不幸的是,它似乎并没有起作用,因为DOM更改只有在函数完成后才会应用(这时已经太晚了...)。 - little_edian
代码中的第一个函数可能是 $(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>

And this the 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);
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接