【问题标题】:Proper Way to Return/Filter Values from AJAX'd PHP Script?从 AJAX 的 PHP 脚本返回/过滤值的正确方法?
【发布时间】:2012-04-10 08:38:44
【问题描述】:

考虑以下几点:

<?php
//daytime_check.php
    $is_daytime = false;
    if ($is_daytime) {
        echo '1';
    } else {
        echo '0';
    }
?>

================================================ ====================================

// javascript/jQuery
$.ajax({
    type: 'POST',
    url: 'daytime_check.php',
    success: function(response) {
        if(response == false) {
            alert('Goodnight, brother');
        } else {
            alert('Day\'s a wastin, brother');
        }            
    },
    error: function() {
        //handle error
    }
});

这就是我迄今为止处理来自我的 AJAX 的 PHP 脚本的响应的方式。我希望有人可以给我一些关于更好方法的提示,因为目前的方法感觉很笨拙。

特别笨重的是在 JS 端处理 PHP 脚本输出的“过滤”。例如:

在这种情况下,来自 PHP 的响应将是一个 JS var response ='0'。现在不能简单地在 JS 中使用if (!response)... 进行过滤,因为显然!response 的计算结果为false,而有趣的是,response == false 的计算结果为true。我想这与类型杂耍有关。

由于我可以从 PHP 中返回内容的唯一方法是文本(echo 语句),所以当我到达 JS 端时,我无法返回正确的真/假值来过滤。有没有更好的方法来处理这个问题?

我希望这至少有点意义。

【问题讨论】:

    标签: php javascript jquery ajax types


    【解决方案1】:

    你仍然可以返回任何你想要的类型。只需使用 JSON 响应。

    // you can return what ever you want via JSON
    die(json_encode(array(
        'isDateTime' => $is_datetime,
        'message'    => 'Some optional message to display',
        'timestamp'  => time()
    )));
    

    这将输出这个字符串:

    {"isDateTime":false,"message":"Some optional message to display","timestamp":1332792739}
    

    在客户端,jQuery 会解析这个响应:

    $.ajax({
        type: 'POST',
        url: 'daytime_check.php',
        dataType: 'json',
        success: function(response) {
            if (response.isDateTime) { ... }
            // typeof response.isDateTime == 'boolean'
            // alert(response.message)         
        },
        error: function() {
            //handle error
        }
    });
    

    【讨论】:

    • 我喜欢这个。同样有趣的是在从 PHP 返回值时如何使用die()。这只是为了解决内存问题而终止脚本吗?
    • 你可以使用echo 或print,随便。我更喜欢die,因为这样我可以确保我只输出 JSON,然后该脚本将关闭。
    • 我喜欢这个主意。我以前没见过这样做。似乎很有道理。
    【解决方案2】:

    如果您只需要在成功处理程序中显示消息,那么为什么不返回消息本身呢?

    <?php
    //daytime_check.php
        $is_daytime = false;
        if ($is_daytime) {
            echo "Day's a wastin', brother";
        } else {
            echo "Goodnight, brother";
        }
    ?>
    
    $.ajax({
        type: 'POST',
        url: 'daytime_check.php',
        success: function(response) {
            alert(response);         
        },
        error: function() {
            //handle error
        }
    });
    

    【讨论】:

    • 好吧,这是为了示例/简洁目的而过度简化的代码。在这种情况下,你的建议会很好。但我正在寻找可以处理所有情况的方法。
    • 返回 1 或 0 很好。您可以检查if(response),它将通过任何非零或非空或非空值。
    • 你能澄清一下吗?当response 实际上指向true/false 的字符串表示为"0" 或"1" 时,可以肯定检查if (response) 将起作用。
    【解决方案3】:

    这是一位聪明的前同事提供的巧妙解决方案。

    以下列方式从您的 PHP 脚本返回值:

    <?php
        // To return an error
        echo json_encode(
            array(
                'success' => false,
                'message' => '[error message here]',
            )
        );
        // To return a successful response
        echo json_encode(
            array(
                'success' => true,
                'response' => [return value here],
            )
        );
    

    这样我们就可以很方便的在JS端做逻辑了:

    $.ajax({
        type: 'POST',
        url: 'ajax_example.php',
        success: function(response) {
                     response = JSON.parse(response);
                     if (!response.success) {
                         alert(response.message);
                     } else {
                         console.log(response.response);    
                     }
        },
        error: function() {
                   //handle error
                   alert('error doing ajax, mate');
               }
        });           
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 2023-03-17
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      相关资源
      最近更新 更多