【发布时间】:2014-11-16 22:03:43
【问题描述】:
在 MVC 中,为什么在 Ajax 回调中返回 Content 有时会失败,而返回 Json 可以工作,即使对于简单的字符串对象也是如此?
即使失败,如果您要在 always 回调中访问数据,数据仍然可用...
更新:
当我将 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
失败的控制器动作(有时)
即使失败,数据仍然可用。
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Content(Foo);
} // end GetFooString
始终有效的控制器操作
public ActionResult GetFooString()
{
String Foo = "This is my foo string.";
return Json(Foo, JsonRequestBehavior.AllowGet);
} // end GetFooString
【问题讨论】:
-
定义“失败”。服务器返回的实际响应是什么?它与“成功”响应有何不同?
-
在Ajax方法中进入错误函数,即使数据返回正确,也没有任何错误。成功响应在 Ajax Success 方法中触发,我在其中提醒数据。
-
尝试将 contentType: "application/json", 添加到您的参数列表中。
-
@silencedmessage:为了让处理程序有任何差异,关于响应的something 必须不同。它的内容、标题等等。
-
@David 如果我在 Ajax 调用中将内容类型更改为
text/xml,则返回内容不会失败。一位同事有一个理论,即 Content 返回一个被翻译为纯文本的字符串对象,而返回 json 显式返回一个 json 对象。
标签: c# jquery ajax asp.net-mvc json