如果 PHP 响应等于某物,如何使 jQuery 警报


How to make jQuery alert if PHP response is equal to something

我有这个jQuery脚本:

$(document).ready(function(){
    $('#submitNewExam').click(function(e){
        e.preventDefault();
        var examName = $('#newExam').val();
        if ($.trim(newExam) != ''){
            $.post('functions/addExam.php', { newExam: examName }, function(data){
                console.log(data);
                if(data =='error'){
                    $('#notify').html(data);
                    $('.alert').toggle();
                }
            });
        }
        $('.add').toggle();
    });
    });

和这个 PHP:

if(isset($_POST['newExam'])){
    if(preg_match('/(<|>|"|%3c|%3e|%22)/', $_POST['newExam'])){
        $a = 'error';
        echo json_encode($a);
    } else {
        echo "something";
    }
}   

我能够输出 PHP 的响应,我无法做的是让 jQuery 读取该响应并在我示例中的响应等于错误时做一些事情。我尝试用 JSON 对响应进行编码,只是将响应作为字符串回显,但这些都不起作用。在console.log中,我可以看到响应,但jQuery什么也没做。

如果不解析 json,您的字符串将包含引号:"error" .

您可以手动解析 json,也可以通过指定数据类型让 jQuery 自动解析:

$.post('functions/addExam.php', { newExam: examName }, function(data){
    console.log(data);
    if(data =='error'){
        $('#notify').html(data);
        $('.alert').toggle();
    }
}, 'json');
    ^^^^ here you specify the data type