运行功能,如果jQuery.ajax等待响应时间足够长 [英] Run function if jQuery.ajax waiting for respond long enough

查看:383
本文介绍了运行功能,如果jQuery.ajax等待响应时间足够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery的code,它只是使一些Ajax请求。

大多数时间只需不到第二个得到回应,这样我就可以显示结果给用户。

但有时(约5%重装的)它需要几秒钟(和我确定这一说法,服务器有点忙)。

我想显示请稍候的文本,当时间超过2秒。但不是当它需要较少的在2秒钟(所以用户不会得到快速显示消息/隐藏混淆)。

如何让它以最有效,最简单的方法是什么?

目前jQuery的code:

  jQuery.ajax({
    网址:loadData.php
    数据类型:JSON,
    键入:GET,
    成功:函数(结果){
        showResultsToUser(结果);
    }
});
 

解决方案

事情是这样的:

  VAR cancelMe = setTimeout的(功能(){
   $('#装载)显示()。 //假设你装元素的ID加载
},2000);在2秒内//显示加载元

jQuery.ajax({
    网址:loadData.php
    数据类型:JSON,
    键入:GET,
    成功:函数(结果){
        showResultsToUser(结果);
        clearTimeout(cancelMe); //如果它尚未运行不运行
        $('#装载)隐藏()。 //隐藏加载元素,如果它的显示
    }
});
 

I've an jQuery code that simply makes some ajax request.

Most of time it takes less than second to get the respond, so I can show the results to the user.

But sometimes (about 5% of reloads) it takes few seconds (and I'm ok with that, the server is a bit busy).

I would like to show "Please wait" text when it takes more then 2 seconds. But not when it takes less then 2 seconds (so user won't get confused by rapid show/hide of message).

How to make it in the most efficient and simplest way?

The current jQuery code:

jQuery.ajax({
    url: "loadData.php",
    dataType: 'json',
    type: 'GET',
    success: function(result){
        showResultsToUser(result);
    }
});

解决方案

Something like this:

var cancelMe = setTimeout(function() {
   $('#loading').show(); // assuming your loading element has the id "loading"
}, 2000); // show loading element in 2 seconds

jQuery.ajax({
    url: "loadData.php",
    dataType: 'json',
    type: 'GET',
    success: function(result){
        showResultsToUser(result);
        clearTimeout(cancelMe); // don't run if it hasn't run yet
        $('#loading').hide(); // hide the loading element if it's shown
    }
});

这篇关于运行功能,如果jQuery.ajax等待响应时间足够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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