Ajax 来自 PHP 的警报响应

Ajax Alert Response from PHP

希望这是一个简单的问题。我实际上使用了一个我在 SO 上找到的例子,但无法弄清楚为什么它不起作用。控制台或任何东西都没有错误。

我有一个 ajax Post 函数用来将数据传递给 php 脚本。

它传递的数据是正确的,但每次响应都是作为错误警报返回。我可以确认服务器端正在获取数据并正确处理它,只是无法弄清楚为什么它从不返回成功响应。

这里是 Ajax:

    $(function () {
        $('#pseudoForm').on('click', '#submit', function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "psu_output.php",
                data: $('#pseudoForm').serialize(),
                datatype: 'json',
                success: function (response) {
                    if(response.type == 'success') {
                        $('#messages').addClass('alert alert-success').text(response.message);
                    } else {
                        $('#messages').addClass('alert alert-danger').text(response.message);
                    }
                }
            });
            return false;
        });
    });
</script>

在我的 php 脚本中,我使用了这个:

<?php

$success = true;

if($success == true) {
    $output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
    $output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}

die($output);
?>

如果您正在使用 JSON 响应,您需要设置 header 以便您的浏览器和 JavaScript 可以正确解释它:

<?php

$success = true;

if ($success == true) {
    $output = json_encode(array(
        'type' => 'success',
        'message' => 'YAY'
    ));
} else {
    $output = json_encode(array(
        'type' => 'error',
        'message' => 'WHOOPS'
    ));
}

header('Content-Type: application/json');
echo $output;

错误是因为您收到的返回数据为 json 但内容类型是一个简单的字符串 (text/html) 所以您需要先 JSON.parse() 收到的数据:

$(function () {
    $('#pseudoForm').on('click', '#submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "psu_output.php",
            data: $('#pseudoForm').serialize(),
            datatype: 'json',
            success: function (response) {
            response = JSON.parse(response);
            if(response.type == 'success') {
                    $('#messages').addClass('alert alert-success').text(response.message);
            } else {
                    $('#messages').addClass('alert alert-danger').text(response.message);
                }
            }
        });
        return false;
    });
});

第二个选项是从 php 本身发送 json headers,从而消除了在 javascript 中解析 JSON 的需要。您可以通过使用以下代码行来做到这一点 BEFORE ECHOING OR PRINTING ANYTHING FROM THE PHP SCRIPT:

header('Content-Type: application/json');

然后

echo $output;

问题是 datatype: 'json' 应该是 dataType: 'json'。 Javascript 区分大小写。