首页 文章

来自PHP的Ajax警报响应

提问于
浏览
0

希望这里有一个简单的问题 . 我实际上使用了我在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);
?>

3 回答

  • 2

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

  • 0

    该错误是因为您收到的返回数据为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头,从而无需在javascript中解析JSON . 您可以使用以下代码行 BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT 来执行此操作:

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

    然后

    echo $output;
    
  • 1

    如果您正在使用JSON响应,则需要设置标头,以便您的浏览器和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;
    

相关问题