从AJAX返回/筛选值的正确方法'd PHP脚本

Proper Way to Return/Filter Values from AJAX'd PHP Script?

本文关键字:方法 脚本 PHP 返回 AJAX 筛选      更新时间:2023-09-26

考虑以下内容:

<?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端时,我无法返回正确的true/false值进行过滤。有更好的方法来处理这个问题吗?

我希望这至少有点道理。

您仍然可以返回任何您想要的类型。只需使用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
//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
    }
});

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

以以下方式从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');
           }
    });           
相关文章: