我有这个 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
关于javascript - 如果 PHP 响应等于某物,如何使 jQuery 发出警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952164/