【问题标题】:PHP's 'echo' does not work rightPHP 'echo' 无法正常工作
【发布时间】:2019-01-13 11:01:18
【问题描述】:

我需要检查一些函数的返回值,我把它们放在一个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 调用没有得到输出

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

        //... 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-');
    }

我得到以下回复:

那么,这是怎么回事?

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 误解了“真” - 所以我们需要将其 enode,例如作为 JSON 字符串:

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

【问题讨论】:

  • “我的 AJAX 调用没有得到输出” - 也许你没有发布的东西有问题,ajax 的东西。
  • 在while循环中有什么意义? / @FunkFortyNiner 仙人掌的美好一天?
  • @Xorifelse 它肯定是哥们 :-)
  • @Xorifelse 如果出现错误就分手,这样后面的函数就不会执行了。
  • @MickaelLeger 循环底部有一个中断...

标签: php if-statement while-loop echo


【解决方案1】:

你响应了一个 AJAX 请求,所以你应该使用json_encode 来确保返回一个有效的 json。

<?php
echo json_encode('true');

在你的情况下它只是一个字符串,但 PHP 正在做一种转换,所以使用 json_encode 更安全。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2012-10-28
    • 2013-10-13
    • 2012-12-06
    • 1970-01-01
    相关资源
    最近更新 更多