javascript 递归 ajax() 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18310338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive ajax() requests
提问by damon
I use jQuery's ajax()
to get information. I call the method when the request is successful. Here is the code:
我使用 jQueryajax()
来获取信息。我在请求成功时调用该方法。这是代码:
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
recursively_ajax();
}
});
}
recursively_ajax();
I make the thread sleep 3 seconds in the back-end. But the console print the message continuously not after 3 seconds. Why is this?
我让线程在后端休眠 3 秒。但是控制台不会在 3 秒后连续打印消息。为什么是这样?
回答by Always Sunny
You can try this with ajax call async:false
你可以用 ajax call async:false 试试这个
var counter=0;
function recursively_ajax()
{
var pass_data=5;
var chartMenu=['VTR','NC','RC','TOCU','TOCO','TR','COA','MP'];
$.ajax({
type:"POST",
async:false, // set async false to wait for previous response
url: "url to server",
dataType:"json",
data:{dataMenu:pass_data},
success: function(data)
{
counter++;
if(counter < chartMenu.length){
recursively_ajax();
}
}
});
}
recursively_ajax();
回答by Arun P Johny
in that case the bug is in the server side code because the server should sent back the response only after 3 seconds.
在这种情况下,错误在服务器端代码中,因为服务器应仅在 3 秒后发回响应。
But I would recommend to use setTimeout()
in the client side to restrict the request frequency
但我建议setTimeout()
在客户端使用来限制请求频率
Try
尝试
function recursively_ajax(){
console.warn("begin");
$.ajax({
type:"GET",
url: "./JvmInfoClass",
success: function(data){
console.warn("get jvm info success");
setTimeout(recursively_ajax, 3000)
}
});
}
recursively_ajax();
回答by damon
It's browser's cacheing problem,I append the date to the url or set the ajax cache:false,the problem is solved.Thank everyone.
是浏览器的缓存问题,我在url后面加上日期或者设置ajax缓存:false,问题解决了。谢谢大家。