我有 index.php 文件,如下所示:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<div id="summary">The returned value will go here</div>
</body>
</html>
ajax.js 的内容应该不断调用/调用 function.php,直到 function.php 返回“1”:
function check(){
return $.ajax({
url: 'function.php',
type:'POST',
success: function(response){
if(response == '1'){
$('#summary').html(response);
}else{
check();
}
},
failure: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
}
});
}
check();
最后是function.php:
<?php
echo "1";
?>
我预计 function.php 只会被调用一次,因为 function.php 返回“1”。然而它不断地调用function.php。
有人可以告诉我如何让它正常工作吗?
最佳答案
代码看起来不错,但 1 个可能的原因是响应可能有前导或尾随空格。
解决方案可能是在比较之前 trim 响应值
if (response.trim() == '1') {//use $.trim(response) if wants to support < IE9 or use a [polyfill](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill)
$('#summary').html(response);
} else {
check();
}
关于javascript - PHP/Ajax/JQuery 响应无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445476/