简体   繁体   中英

ajax - How to receive data both html and json from server?

I have referenced this topic , but it doesn't solve my problem.

I'm using mvc 5 with c#. I have usually used this code to receive data from server with data type is json .

$.ajax({
   url: "/MyController/MyAction",
   type: "POST",
   dataType: "json",
   success: function (data) {
      if (data.result) {
         alert('successfull');
      }
      else {
         alert(data.ex);
      }
   }
});

and Controller code:

[httppost]
public ActionResult MyAction()
{
   try
   {
      return Json(new { result = "true", ex = "" });
   }
   catch (Exception e)
   {
      return Json(new { result = "false", ex = e.Message });
   }
}

I use this way for data type is html:

$.ajax({
   url: "/MyController/MyAction",
   type: "POST",
   dataType: "html",
   success: function (data) {
      $(".myDiv").append(data);
   }
});

and the Controller should be:

[httppost]
public ActionResult MyAction()
{
   return PartialView("_MyPartialView");
}

My question is: Is there any way to combine all of them to one?

Something is like this:

$.ajax({
   url: "/MyController/MyAction",
   type: "POST",
   dataType: "json" or "html",
   success: function (data) {
      if (data.result) {
         $(".myDiv").append(data);
      }
      else {
         alert(data.ex);
      }
   }
});

and the imagination Controller code:

[httppost]
public ActionResult MyAction()
{
   try
   {
      return PartialView("_MyPartialView");
   }
   catch (Exception e)
   {
      return Json(new { result = "false", ex = e.Message });
   }
}

Yes you can:

@section scripts
{
    <script>
        $(function() {
            $.ajax({
                url: "/Home/MyAction",
                type: "POST",
                success: function (data) {
                    if (!data.result) {
                        $(".myDiv").append(data);
                    }
                    else {
                        alert(data.ex);
                    }
                }
        });
        });
    </script>
}

So if the data doesn't contain anonymouse object, It means that it contains the HTML returned by PartialView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM