我有一个JavaScript函数来调用ajax.现在我需要在这个函数中添加时间,就像调用服务花费的时间超过了ajax调用应该超时并显示默认消息.我不想在其中使用Jquery.
这是我的代码:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)
以下是如何处理超时的示例:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
Run Code Online (Sandbox Code Playgroud)
在 IE8 中,您可以向 XMLHttpRequest 对象添加超时事件处理程序。
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Run Code Online (Sandbox Code Playgroud)
使用 javascript 框架来做到这一点,我不知道你为什么不使用一个,你喜欢不必要的工作吗?:)
| 归档时间: |
|
| 查看次数: |
705 次 |
| 最近记录: |