我在PHP中使用jQuery Ajax。当我使用jQuery Ajax post时,它会向PHP(服务器)发送请求。在我的PHP代码中,我想返回状态成功或错误。如果它出错,发送错误代码和错误消息,否则,它成功返回成功代码和消息。
我如何在PHP的jQuery Ajax中做到这一点?
编辑:
$.post(url, { id: id },
function(data) {
// success code do here.
});
答案 0 :(得分:4)
只需使用json编码返回数组...
header('Content-Type: application/json');
$array = array("status"=>"success");
echo json_encode($array);
exit();
退出是为了防止任何进一步的回声。
在你的ajax ..
$.post(url, { id: id },
function(data) {
alert(data.status);
}, 'json');
data.status等于你的php数组密钥状态..
只是抓住Ajax错误......你可以设置简单..
header('Content-Type: application/json');
echo "string whithout json_encode";
exit();
在这种情况下,将你的ajax改为......
$.post(url, { id: id },function(data) {}, 'json')
.success(function(data) { alert("success"); })
.error(function(data) { alert("error"); });
答案 1 :(得分:0)
只需使用echo
返回它PHP:
if($check == 0){
echo 'success';
exit();
}
else {
echo 'failed';
exit();
}
jquery :
$.post(url, { id: id },
function(data) {
alert(data);
});