在同步Ajax的负载指示 [英] Loading Indicator on Synchronous Ajax

查看:156
本文介绍了在同步Ajax的负载指示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX使用jQuery在我的网站,需要显示进度/负荷指标。

我的dilemna是这样的:

  • 同步AJAX锁定浏览器,所以我不能做任何事情(如显示加载指示器),直到内容返回,到那个时候已经太晚了
  • 在我使用JSON作为返回数据的类型和设置异步=真返回一个空的响应字符串
  • 在我的整个架构依赖于返回类型被JSON格式

我似乎无法找到任何办法让JS给用户的指示的东西是在进步,只是做一个警报()。 (出于某种原因,警报不工作)。

有什么建议?

我的code:

JS

  VAR jqXHR = $阿贾克斯(
{
    键入:POST,
    网址:网址,
缓存:假的,
    数据:参数的参数,可以//阵列
    异步:假的,// responseText的是空的,如果设置为true
    数据类型:JSON,
    错误:函数()
    {
        警报(阿贾克斯POST请求到下面的脚本失败:+网址);
    }

});

VAR HTML = jqXHR.responseText;
 

PHP

  $收益率=阵列();
$返回['状态'] = 1;
$返回['消息'] =一些HTML这里......;
回声json_en code($返程);
 

解决方案

您可以使用jQuery的全局AJAX事件处理程序。此链接描述了他们的详细信息:

<一个href="http://api.jquery.com/category/ajax/global-ajax-event-handlers/">http://api.jquery.com/category/ajax/global-ajax-event-handlers/

  $(文件).ajaxStart(函数(){
    $(#加载)显示()。
});

$(文件).ajaxComplete(函数(){
    $(#加载)隐藏()。
});
 

I'm using ajax with jQuery on my site and need to show a progress / loading indicator.

My dilemna is this:

  • Synchronous AJAX locks the browser, so I cant do anything (e.g. show a loading indicator) till the contents are returned, by which time it is too late
  • I am using JSON as the return data type and setting async = true returns an empty response string
  • my whole framework relies on the return type being JSON-formatted

I cannot seem to find any way to get JS to give the user an indication that something is in progress, except for doing an alert(). (For some reason an alert does work).

Any suggestions?

My code:

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);

解决方案

You can use the Jquery Global Ajax Event Handlers. This link describes them in detail:

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

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

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

这篇关于在同步Ajax的负载指示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆