PHP的“ echo”无法正常工作

时间:2018-08-06 13:07:00

标签: php if-statement while-loop echo

我需要检查一些返回函数的值,这些返回值放在while循环中:

    //should be true if an error comes up (a function returns false)
    $error = false;

    while ($error == false) {
        if (!$this->check_date()) {
            $this->log('bad date');
            $error = true;
            break;
        }

        if (!$this->check_location()) {
            $this->log('bad location');
            $error = true;
            break;
        }

        if (!$this->check_abc()) {
            $this->log('bad abc');
            $error = true;
            break;
        }

        //... more if's

        break;
    }

    //No error - great
    if ($error == false) {
        //Answer to my AJAX call
        echo "true";
    } else {
        $this->log('-There is an error-');
    }

那么,出什么问题了?

我没有收到AJAX调用的输出

enter image description here

但是如果我把一个回声“测试”;在这里:

        //... more if's

        break;
    }

echo "test";

    //No error - great
    if ($error == false) {
        //Answer to my AJAX call
        echo "true";
    } else {
        $this->log('-There is an error-');
    }

我得到以下答复:

enter image description here

那么,这是怎么回事?

AJAX代码:

    $.ajax({
        url: "index.php",
        type: "POST",
        async: false,
        data: "do=this",
        success: function (answer) {

            console.log(answer);

        },
        error: function (jXHR, textStatus, errorThrown) {                
            console.log("error" + errorThrown);
        }
    });

谢谢您的帮助:)

解决方案:PHP似乎误解了“ true”,因此我们需要对其进行enode处理,例如作为JSON字符串:

    //No error - great
    if ($error == false) {
        //Answer to my AJAX call
        echo json_encode("true");
    } else {
        $this->log('-There is an error-');
    }

1 个答案:

答案 0 :(得分:2)

您响应AJAX请求,因此应使用json_encode以确保返回有效的json。

<?php
echo json_encode('true');

在这种情况下,它只是一个字符串,但是PHP进行了一种类型转换,因此使用json_encode更安全。

相关问题