gpt4 book ai didi

jquery - Ajax场景下如何返回错误

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

我正在使用带有 jQ​​uery 的 ASP.NET MVC。我有以下 MVC 操作,它返回成功的部分页面。关于应用程序错误,我不确定要发送什么内容以便在客户端正确处理它:

public ActionResult LoadFilterSet(int filterSetId)
{
try
{
BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID);
GeneralHelper.LoadBreadCrumbManager(bcManager, filterSetId);

ViewData["BreadCrumbManager"] = bcManager;
return View("LoadFilterSet");
}
catch (Exception ex)
{
return Content("");
}
}

以下是我的 jQuery ajax 调用。请注意,我正在检查数据长度以确保没有错误。请建议我一个更好的方法来做到这一点。

$.ajax({
type: "GET",
dataType: "html",
async: true,
data: ({ filterSetId: selectedId }),
url: link,
contentType: "text/html; charset=utf-8",
success: function(data, textStatus) {
if (data.length > 0) {
// Clear the local filters first.
clearLocalFilters();
$('td.selected-filters table.filters-display').append(data);
}
}
});

最佳答案

我会在您的 ajax 调用设置中添加一个错误函数。让服务器确定要显示的错误消息并将其传递给 ajax 错误处理程序并让它显示它。

success: function(data, textStatus) {     
// Clear the local filters first.
clearLocalFilters();
$('td.selected-filters table.filters-display').append(data);
},
error: function (data) {
alert(data.responseText); // use any display logic here
}

在 Controller 的操作中,如果发现错误

Response.StatusCode = (int)HttpStatusCode.BadRequest; 
return Content(errorMessage, MediaTypeNames.Text.Plain);

关于jquery - Ajax场景下如何返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2832510/

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