在 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/