2016-12-07 96 views
-1

有没有办法在Javascript/jQuery中创建一个POST请求,并使用该变量作为setTimeout时间?异步返回数据

$.post('file.php', { action: "gettimeout"}, 
function(time){ 
    return time; 
}); 
setInterval(function(){ alert("Hello"); }, time); 

是我想要做的。

我目前能够做到,但我正在同步进行。

var time = $.ajax({ 
    type: 'POST', 
    url: 'file.php', 
    data: {action: "gettimeout"}, 
    async: false 
}); 
return Number(time.responseText); 
setInterval(function(){ alert("Hello"); }, time); 
+1

你应该使用回调。看看这个答案:http://stackoverflow.com/a/14220323/1056133 – jayantS

回答

1

只要把你的电话给setInterval(或setTimeout)Ajax回调函数中:

$.post('file.php', { action: "gettimeout"}, function(time){ 
    setInterval(function(){ alert("Hello"); }, time); 
}); 

NB:有在Ajax回调函数返回值,没有任何意义。见How do I return the response from an asynchronous call