我有以下代码,但它似乎无法正常工作。我不明白为什么。
JS
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
setTimeout(updateBoard, 1000);
};
PHP
if(isset($_POST['codes'])) {
echo "test";
}
答案 0 :(得分:1)
您可以尝试以下方法:
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
setTimeout(updateBoard, 1000); //calling the function after 1 sec after we get the response
}
});
};
updateBoard(); //calling it right away
答案 1 :(得分:0)
正如@Smiranin所说,只需在函数外部调用 setTimeout :
var updateBoard = function(){
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response)
}
})
};
setTimeout(updateBoard, 1000);
或者只使用 setInterval 而不是SetTimeout
setInterval(updateBoard, 1000);
答案 2 :(得分:0)
如果要在每秒钟内运行此命令,可以尝试使用setInterval()。
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
};
setInterval(updateBoard, 1000);

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;