ajax post不捕获错误,总是捕获成功
我有一个ajaxpost方法将新记录添加到数据库中,该过程本身工作正常,我的服务器端代码捕获错误(重复输入等)。当eror发生时,ajax方法不会“看到”它,总是调用“success”函数。这是我的ajax post方法ajax post不捕获错误,总是捕获成功,ajax,asp.net-mvc,error-handling,controller,actionmethod,Ajax,Asp.net Mvc,Error Handling,Controller,Actionmethod,我有一个ajaxpost方法将新记录添加到数据库中,该过程本身工作正常,我的服务器端代码捕获错误(重复输入等)。当eror发生时,ajax方法不会“看到”它,总是调用“success”函数。这是我的ajax post方法 $.ajax({ 网址:'@url.Action(“添加”、“组织”), 数据:$form.serialize(), async:true, 键入:“POST”, 错误:函数(returnval){ $form.parents('.bootbox').modal('hide'
$.ajax({
网址:'@url.Action(“添加”、“组织”),
数据:$form.serialize(),
async:true,
键入:“POST”,
错误:函数(returnval){
$form.parents('.bootbox').modal('hide');
bootbox.alert('保存此组织时出错:'+returnval['responseText']);
},
成功:函数(returnval){
//隐藏对话框
$form.parents('.bootbox').modal('hide');
bootbox.alert(“新组织已成功添加”);
}
})
更新您的成功方法
success: function (returnval)
{
if(returnval.success=true)
{
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
if(returnval.success=false)
{
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
}
}
希望有帮助 您没有做错任何事情。事实上,您的代码也运行良好 原因是成功函数总是在执行,因为AJAX调用成功地进行了 若AJAX调用失败,那个么只有错误函数将被执行 示例假设您将Ajax属性contentType设置为错误 例如:-内容类型:'xyzfds' 在某些情况下,或者可能是因为任何其他ajax方法属性的值错误。所以无需担心 如果您想显示错误信息,请按照以下方法操作,这可能会对您有所帮助。谢谢
success: function (returnval) {
if(returnval!=null){
if(returnval.success){
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
if(returnval.success==false){
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
}
}
}
您的方法中没有任何地方会抛出异常,因此它不会命中
error
函数。您需要检查returnval的值。success必须将returnval.success=false更改为returnval.success==false,但这就成功了,非常感谢,我已经想了一段时间了。我不太明白错误的意义:函数部分,但如果它实际上不起作用:-(如果ajax调用中出现错误,则会命中错误函数,但ajax调用运行良好并返回成功。现在需要在成功方法中添加检查点。