javascript - PHP/Ajax/JQuery 响应无法正常工作

标签 javascript php jquery ajax

我有 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/

相关文章:

javascript - CollectionView 中的 Ember JS 和 Handlebars 助手

javascript - 如何在生产中获取绝对 URL?

javascript - 简单的 Accordion 定位

javascript - Javascript 如何处理将 setInterval() 分配给变量?

javascript - 使用 RowCommand 事件在 GridView 上编辑单击弹出 Bootstrap 模型

javascript - NodeJS 模块初始化

php - 如何使用函数在php中制作自动版权网页页脚

php - 在 HTML 中包含 php 脚本

php - 理解 Laravel : Please explain "->with(' i', ($request->input ('page' , 1) - 1) * 5); ”

javascript - 如何在 jquery 中启用和禁用下拉值