在同步Ajax上加载指示符

lit*_*ian 9 ajax jquery json loading synchronous

我在我的网站上使用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;
Run Code Online (Sandbox Code Playgroud)

PHP

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

Mp *_*ega 17

您需要在调用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);
Run Code Online (Sandbox Code Playgroud)

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

  • 好吧,我最终使用了超时并修补了我的所有代码,并且效果很好。所以感谢你给我一个刺激让我到达那里(会投票给你,但没有足够的声望点!) (2认同)

Baa*_*ali 9

您可以使用Jquery Global Ajax事件处理程序.此链接详细描述了它们:

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

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

$(document).ajaxComplete(function () {
    $("#loading").hide();
});
Run Code Online (Sandbox Code Playgroud)