我正在调用一个函数,使用jQuery ajax函数以毫秒为间隔调用webservice。如果第一个请求之一较慢,则它们会重叠,成功函数将使用旧的请求响应。
这是我的ajax调用函数:
function runRequest(url, request, token, handleSuccess, handleError) {
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
headers: {
"Authorization": "Basic " + btoa(/* ... */),
"Content-Type": "application/json"
},
success: function (data, status, xhr) {
handleSuccess(data);
},
error: function (xhr, status, error) {
handleError(xhr);
}
});
}
如何预防?我试图节省创建请求的时间,管理那个时间到成功和错误函数,检查它是否响应,但它不会工作..
同步的ajax请求不是选项..:/
答案 0 :(得分:3)
解决此问题的快捷方法是为您的请求添加时间戳或计数器,并在handleSuccess
时更新。
handleSuccess = (function () {
// closure scope this variable so only handleSuccess sees it.
var latest = 0;
return function handleSuccess(timestamp, data) {
if (timestamp < latest) { return; }
latest = timestamp;
// the normal body of handleSuccess goes here
};
})();
function runRequest(url, request, token, handleSuccess, handleError) {
var timestamp = (new Date()).valueOf();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
headers: {
"Authorization": "Basic " + btoa(/* ... */),
"Content-Type": "application/json"
},
success: function (data, status, xhr) {
handleSuccess(timestamp, data);
},
error: function (xhr, status, error) {
handleError(xhr);
}
});
}
您可以在此演示中看到handleSuccess包装器的工作方式:https://jsfiddle.net/n6j1psut/
答案 1 :(得分:1)
正如我评论的那样:
var count = 0;
function runRequest(url, request, token, handleSuccess, handleError, index) {
count = index;
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
headers: {
"Authorization": "Basic " + btoa(/* ... */),
"Content-Type": "application/json"
},
success: function (data, status, xhr) {
if(index == count){
handleSuccess(data);
}
},
error: function (xhr, status, error) {
if(index == count){
handleError(xhr);
}
}
});
}
runRequest(..., count++);
答案 2 :(得分:0)
你需要检查一下你是否已经在进行中并等到它完成了例如:
var isRunning = false;
function call()
{
if(isRunning)
return; // still working... please wait.
isRunning = true;
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
headers: {
"Authorization": "Basic " + btoa(/* ... */),
"Content-Type": "application/json"
},
success: function (data, status, xhr) {
handleSuccess(data);
isRunning = false;
},
error: function (xhr, status, error) {
handleError(xhr);
isRunning = false;
}
});
}