gpt4 book ai didi

ajax - ajax发布不捕获错误,总是捕获成功

转载 作者:行者123 更新时间:2023-12-03 08:50:08 25 4
gpt4 key购买 nike

我有一个ajax post方法可以将新记录添加到数据库中,该过程本身可以正常运行,并且我的服务器端代码会捕获错误(重复输入等)。当发生错误时,ajax方法不会“看到”它,始终会调用“成功”功能。这是我的ajax发布方法

$.ajax({
url: '@Url.Action("Add", "Organisation")',
data: $form.serialize(),
async: true,
type: 'POST',
error: function (returnval) {
$form.parents('.bootbox').modal('hide');
bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
},
success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}
})


还有我 Controller 上的 Action 方法
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Add(OrganisationEditCreateViewModel data)
{
InsertOrganisationRequest request = new InsertOrganisationRequest();
IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
var model = mapper.Map<OrganisationEditCreateViewModel, OrganisationDto>(data);
request.organisation = model;
var response = this._organisationService.InsertOrganisation(request);
if (response.isSuccess)
{
return Json(new { success = true, responseText = "New organisation added successfully" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false, responseText = "Error adding new organisation : Invalid input" }, JsonRequestBehavior.AllowGet);
}

因此,当我插入重复的记录时,服务器端代码会捕获该记录,并将此代码分支返回给我的ajax调用

return Json(new {success = false,responseText =“添加新组织时出错:” + response.Message},JsonRequestBehavior.AllowGet);

但是ajax调用总是调用这段代码

success: function (returnval) {
// Hide the dialog
$form.parents('.bootbox').modal('hide');
bootbox.alert('New Organisation successfully added');
}


错误部分永远不会被调用,我在做什么错?

最佳答案

更新您的成功方法!

 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发布不捕获错误,总是捕获成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com