[英]ajax - How to receive data both html and json from server?
我已经参考了这个主题 ,但是并不能解决我的问题。
我在C#中使用MVC 5。 我通常使用此代码从数据类型为json
服务器接收数据。
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "json",
success: function (data) {
if (data.result) {
alert('successfull');
}
else {
alert(data.ex);
}
}
});
和控制器代码:
[httppost]
public ActionResult MyAction()
{
try
{
return Json(new { result = "true", ex = "" });
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
我使用这种方式的数据类型是html:
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
success: function (data) {
$(".myDiv").append(data);
}
});
控制器应为:
[httppost]
public ActionResult MyAction()
{
return PartialView("_MyPartialView");
}
我的问题是:有没有办法将所有这些组合在一起?
像这样:
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "json" or "html",
success: function (data) {
if (data.result) {
$(".myDiv").append(data);
}
else {
alert(data.ex);
}
}
});
和想象力控制器代码:
[httppost]
public ActionResult MyAction()
{
try
{
return PartialView("_MyPartialView");
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
是的你可以:
@section scripts
{
<script>
$(function() {
$.ajax({
url: "/Home/MyAction",
type: "POST",
success: function (data) {
if (!data.result) {
$(".myDiv").append(data);
}
else {
alert(data.ex);
}
}
});
});
</script>
}
因此,如果data
不包含匿名对象,则意味着它包含PartialView
返回的HTML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.