我试图通过ajax函数的参数传递4个变量,但由于某种原因它不接受它。我试图传递的变量是 url、action、id 和超时(以毫秒为单位)。如果有人知道我做错了什么,请纠正我。谢谢。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax(url,action,id,timeout) {
$.ajax({
type: "POST",
url: url,
data:{action: action},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
setTimeout(myAjax, timeout);
}
});
}
</script>
<body onload="myAjax('testing.php','call_this','my_div',2000)">
<div id="my_div"></div>
</body>
这是代码的工作版本,没有通过参数传递变量,而是将它们放在函数本身中:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action: 'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( 'my_div' ).innerHTML = data;
setTimeout(myAjax, 2000);
}
});
}
</script>
<body onload="myAjax()">
<div id="my_div"></div>
</body>
最佳答案
像这样重写 setTimeout()
调用:
setTimeout(function() {
myAjax(url,action,id,timeout);
}, timeout);
关于javascript - 通过 PHP 参数将变量传递给 AJAX 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632927/