我有一个Web应用程序,其中有许多Ajax组件在页面内经常刷新(它是各种各样的仪表板).
现在,我想为页面添加功能,以便在没有Internet连接时,页面的当前内容不会更改,并且页面上会显示一条消息,指出页面处于脱机状态(当前,这些不同的小工具都在页面尝试刷新自己,发现没有连接,他们的旧数据消失了).
那么,最好的方法是什么?
解决方法:
处理此问题的一种方法可能是使用显式超时方法扩展XmlHTTPRequest对象,然后使用它来确定您是否在脱机模式下工作(即,对于不支持navigator.onLine的浏览器).以下是我在一个站点(使用Prototype库的站点)上实现Ajax超时的方法. 10秒(10,000毫秒)后,它将中止调用并调用onFailure方法.
/**
* Monitor AJAX requests for timeouts
* Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
*
* Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure
* method (if it exists), passing an error code to the function.
*
*/
var xhr = {
errorCode: 'timeout',
callInProgress: function (xmlhttp) {
switch (xmlhttp.readyState) {
case 1: case 2: case 3:
return true;
// Case 4 and 0
default:
return false;
}
}
};
// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
onCreate: function (request) {
request.timeoutId = window.setTimeout(function () {
// If we have hit the timeout and the AJAX request is active, abort it and let the user kNow
if (xhr.callInProgress(request.transport)) {
var parameters = request.options.parameters;
request.transport.abort();
// Run the onFailure method if we set one up when creating the AJAX object
if (request.options.onFailure) {
request.options.onFailure(request.transport, xhr.errorCode, parameters);
}
}
},
// 10 seconds
10000);
},
onComplete: function (request) {
// Clear the timeout, the request completed ok
window.clearTimeout(request.timeoutId);
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。