新手 - 问题 -
试图解决的问题:如果有一些打开的连接没有被 XMLHttprequest 关闭,我们想要中止它们。
在有 Ajax 调用的 javascript 文件中,我需要为每个调用启动一个计时器,并在成功和失败回调中清除计时器。想要确保 - 如果计时器触发,则意味着请求尚未返回,因此应该中止。对于尽管中止的情况,请求可能会返回 - 想要丢弃它们。想要添加一个标志,在处理之前检查成功和失败回调,并适当处理。
想像这样添加一个计时器:
var timer = setTimeout(function() { // Start a timer. If triggered,
timedout = true; // set a flag and then
request.abort(); // abort the request.
},
timeout); // time specified
但是在下面给出的现有代码中,我发现很难理解从哪里开始我的计时器和中止。
this.ajaxCall = function(urlSuffix, type, data, successCallback, errorCallback, callbackParam, logFlag)
{
if (!successCallback) {
throw "A successCallback must be supplied";
}
if (!errorCallback) {
throw "An errorCallback must be supplied";
}
var st = 0;
if (logFlag !== false)
st = LogMessageTestCL(urlSuffix + " - start: " + type, -1);
$.ajax({
url: urlRoot + urlSuffix,
type: type,
data: data,
cache: false,
success: function(msg) {
try {
if (logFlag !== false)
LogMessageTestCL(urlSuffix + " - end: " + type, st);
successCallback(msg, callbackParam);
}
catch (e) {
// this will only fail when the calling page is unloaded before the call returns, so no need to log this
}
},
error: function(xhr,status) {
try {
if (logFlag !== false)
LogMessageTestCL(urlSuffix + " - error end: " + type, st);
if (status === "timeout") {
alert("30 sec time out");
LogMessageTestCL("callback timed out");
return;
}
else if (status === "error") {
if (xhr.status != 200) {
errorCallback(xhr, callbackParam);
}
}
else
errorCallback(xhr, callbackParam);
}
catch (e) {
// this will only fail when the calling page is unloaded before the call returns, so no need to log this
}
}
});
}
任何帮助是极大的赞赏。