gpt4 book ai didi

jquery - 如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?

转载 作者:行者123 更新时间:2023-12-03 22:00:37 24 4
gpt4 key购买 nike

我有一些看起来像这样的 jQuery:

$.ajax({
type: "POST",
url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
contentType: "application/json",
success: refreshTransactions,
error: function(xhr, ajaxOptions, thrownError) {
alert("Failed to cancel subscription! Message:" + xhr.statusText);
}
});

如果被调用的操作导致异常,它最终会被 Global.asax Application_Error 捕获,其中我有一些如下代码:

var ex = Server.GetLastError();
if (Request.ContentType.Contains("application/json"))
{
Response.StatusCode = 500;
Response.StatusDescription = ex.Message;
Response.TrySkipIisCustomErrors = true;
}
else
{
// some other way of handling errors ...
}

当我执行发布请求的脚本时,Request.ContentType 始终是空字符串,因此不会命中第一个 if block 。我是否应该在 ajax“contentType”中放入其他值?或者我还有另一种方法来告诉 asp.net 内容类型应该是“application/json”?

澄清

我试图实现的目标是将异常消息传递回ajax错误事件。目前,即使 IF block 被绕过,错误事件也会正确引发警报框,但消息为“未找到”。

如您所见,我正在尝试将异常消息设置为 Response.StatusDescription,我相信 ajax 错误中的 xhr.statusText 已设置为该值。

最佳答案

根据这篇文章:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ “当没有包含数据时,jQuery 无法正确设置指定的内容类型。”

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/WebMethodName",
data: "{}",
dataType: "json"
});

关于jquery - 如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2202857/

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