我已经向我的login.php 文件写入了一个ajax post 请求,该请求会回显“错误”或“成功”等内容。
我不太确定如何使用这个函数,因为我也想检查失败和其他内容,然后将文本添加到错误框中。
有什么想法吗?
这是我当前的代码:
$('#submit').click( function() {
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: $('form#loginForm').serialize(),
beforeSend:function(){
launchPreloader();
},
complete:function(){
stopPreloader();
},
success: function(data) {
window.href("chat.php");
}
});
});
最佳答案
来自jQuery $.ajax() documentation ...
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
以您的代码为例......
$('#submit').click( function() {
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: $('form#loginForm').serialize(),
beforeSend:function(){
launchPreloader();
},
complete:function(){
stopPreloader();
},
success: function(data) {
window.href("chat.php");
}
}).done(function() {
alert('Done!');
}).fail(function() {
alert('Fail!');
});
});
关于php - 检查ajax请求的失败和成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18191760/