我有一些服务器端代码,在完成结账时返回true或false。通过控制台日志,它看起来像{"success": true, "message": "Added to db"}
。我怎样才能正确地写出ajax的成功条件,如果答案是真的,那么我们会做点什么,否则我们会做点什么呢?
处理程序php
echo json_encode(['success' => true, 'message' => 'Added to db']);
}
} else {
echo json_encode(['success' => false, 'message' => 'Wrong captcha']);
}
的index.php
$(document).ready(function() {
$('#submit').click(function() {
var username = $('#username').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#captcha').val();
if(username === ''){
alert('Please input data in all fields');
} else {
$.ajax({
type: "POST",
cache: false,
url: '/data/insert.php',
data: {username: username, email: email, message: message, captcha: captcha},
success: function(response) {
console.log(response);
}
});
}
});
});
答案 0 :(得分:0)
Ajax将查看http标头以确定是否存在错误。您可以在验证响应时在服务器上设置错误代码:
if ($someCondition) { // If the request is good
echo json_encode(['message' => 'Added to db']);
} else { // Request is bad. You can add any number of conditions and return any number of errors
header('HTTP/1.1 400 Bad Request');
exit(json_encode(['message' => 'Some error message', 'code' => 400]));
}
您可以看到客户端错误列表here
然后,对于你的ajax,有一个特定的错误处理函数:
$.ajax({
type: "POST",
cache: false,
url: '/data/insert.php',
data: {username: username, email: email, message: message, captcha: captcha},
success: function(response) {
console.log(response.message);
},
error: function(response) {
alert(response.message);
}
});
答案 1 :(得分:0)
$(document).ready(function() {
$('#submit').click(function() {
var username = $('#username').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#captcha').val();
if(username === ''){
alert('Please input data in all fields');
}
else {
$.ajax({
type: "POST",
cache: false,
url: '/data/insert.php',
data: {username: username, email: email, message: message, captcha: captcha},
success: function(response) {
if(response.success == true){
// do some thing
}else{
// do some thing
}
}
});
}
});
});