成功ajax:如果是200状态代码运行功能其他功能
我不知道为什么不工作...我使用$.ajax
运行file.php并通过它(POST
)输入值 此文件.PHP工作,但我的AJAX功能不起作用:成功ajax:如果是200状态代码运行功能其他功能
$.ajax({
type: 'POST',
url: 'file.php',
data: { email: $('#andressemail').val() },
success: function(data,status){
if(status === '200'){
newmessage();
}
else{
erroremessage();
}
}
});
funtion newmessage(){
alert('ok');
}
funtion erroremessage(){
alert('no');
}
的file.php工作正常(它在我的通讯增加了一个用户),但$.ajax
不起作用,状态码是不是200
为什么?
尝试以下操作以获取状态代码,使用xhr.status为的StatusCode:
$.ajax({
type: 'POST',
url: 'file.php',
data: { email: $('#andressemail').val() },
success: function(xml, textStatus, xhr) {
alert(xhr.status);
if(xhr.status === '200'){
newmessage();
}
else{
erroremessage();
}
}
});
funtion newmessage(){
alert('ok');
}
funtion erroremessage(){
alert('no');
}
你的代码是上帝,但是“xhr.status === 200”(不是'200')否? – Borja
是的......你有没有提醒xhr.status,哪个值会在失败时返回? –
使它成为:xhr.status === 200 –
成功函数只有在HTTP响应已经200
运行。您还需要使用错误函数以及在HTTP响应未正确完成时触发。改变你的代码看起来像:
function newmessage(data, textStatus, jqXHR){
alert('ok');
}
function erroremessage(data, textStatus, jqXHR){
alert('no');
}
$.ajax({
type: 'POST',
url: 'file.php',
data: { email: $('#andressemail').val() },
success: newmessage,
error: erroremessage
});
处理$.ajax
最好的办法是这样的:
var _ajax = function(url, data, type){
return $.ajax({
type: type,
url: url,
data: data,
});
}
var data = { email: $('#andressemail').val() };
_ajax('file.php', data, 'POST')
.success(function(res, statusTitle, xhr){
// res: response from server
// statusTitle = 'success', ...
// xhr: XHR object, for your case, xhr.status will be 200
});
可以使用.error(function(){...})
太,(也.done
);
试试这个:status =='success' –