c# - MVC Controller 返回内容与返回 Json Ajax

标签 c# jquery ajax asp.net-mvc json

在 MVC 中,为什么返回 Content 有时会在 Ajax 回调中失败,而返回 Json 有效,即使对于简单的字符串对象也是如此?

即使失败,如果您在始终回调中访问它,数据仍然可用...

更新:

当我将 ajax 调用中的 contentType 设置为 text/xml 时,响应将不再输入错误消息。

AJAX:

$.ajax({
    cache: false,
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    url: "/MyController/GetFooString",
    data: { },
    success: function (data) {
        alert(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Ajax Failed!!!");
    }
}); // end ajax call

Controller 操作失败(有时)

即使失败,数据仍然可用。

public ActionResult GetFooString()
{
    String Foo = "This is my foo string.";
    return Content(Foo);
} // end GetFooString

始终有效的 Controller 操作

public ActionResult GetFooString()
{
    String Foo = "This is my foo string.";
    return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString

最佳答案

使用 Content(Foo); 发送没有 mime 类型 header 的响应。发生这种情况是因为您在使用此重载时没有设置 ContentType。当未设置 Content-Type 时,jQuery 将尝试猜测内容类型。当发生这种情况时,它是否能够成功猜测取决于实际内容和底层浏览器。参见 here :

dataType (default: Intelligent Guess (xml, json, script, or html))

Json(...) 另一方面 explicitly将内容类型设置为 "application/json" 因此 jQuery 确切地知道将内容视为什么。

如果使用 2nd overload,您可以从 Content 获得一致的结果并指定一个 ContentType:

return Content(Foo, "application/json"); // or "application/xml" if you're sending XML

但是如果你总是处理 JSON,那么更喜欢使用 JsonResult

return Json(Foo, JsonRequestBehavior.AllowGet); 

关于c# - MVC Controller 返回内容与返回 Json Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25982552/

相关文章:

c# - 检测它是否是字典并且键是否可从特定类型分配

c# - 检查状态生存时间是否未过期

jquery - $.getJSON 不返回 MVC3 的响应

Jquery 邮政编码服务区验证问题。

javascript - Angular UI 多个弹出窗口,提交后以编程方式关闭单个弹出窗口

javascript - 如何在不使用选择器刷新网页的情况下导航到其他网站或网页?

c# - 如何拥有适用于控制台和 wpf 的 calibburn 应用程序?

c#拒绝访问以创建新文件

jquery - 使用 .next() 查找并显示下一个 div

javascript - 获取完整页面而不仅仅是 Ajax 响应片段