gpt4 book ai didi

jquery - 如何从application_error返回AJAX错误函数?

转载 作者:行者123 更新时间:2023-12-01 07:44:54 24 4
gpt4 key购买 nike

下面的代码最终出现在 AJAX success 函数中。为什么?它应该执行 error 函数。我究竟做错了什么?

$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
if (callback)
callback(data);

$.LoadingOverlay("hide");
},
error: function (event, jqxhr, settings, thrownError) {
var t = "";

}
});
protected void Application_Error(object sender, EventArgs e)
{
var ctx = HttpContext.Current;

var exception = ctx.Server.GetLastError();

bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
Context.ClearError();
if (isAjaxCall)
{
//Context.Response.ContentType = "application/json";
Context.Response.StatusCode = 200;
Context.Response.Write(
new JavaScriptSerializer().Serialize(
new { error = exception.Message }
)
);
}
}

Controller 只是抛出异常:

throw new Exception("faulty");

最佳答案

当收到 2xx 以外的任何 HttpStatusCode 时,将执行 $.ajaxerror 处理程序。考虑到这一点,您可以返回 500 Internal Server Error,如下所示:

protected void Application_Error(object sender, EventArgs e)
{
var ctx = HttpContext.Current;
var exception = ctx.Server.GetLastError();
bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
Context.ClearError();

if (isAjaxCall)
{
Context.Response.StatusCode = 500; // note the change here
Context.Response.Write(new JavaScriptSerializer().Serialize(new { error = exception.Message }));
}
}

关于jquery - 如何从application_error返回AJAX错误函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081432/

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