AJAX MVC 伺服器返回Json資料,用戶端擷取Json資料,mvcjson
<>
控制器 Controller
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Script.Serialization;namespace MvcApplication2.Controllers{ public class HomeController : Controller { public ActionResult Index() { return View(); } //---------------------------------第一種寫法:伺服器返回一個Json對象 public ActionResult GetData1() { JsonResult json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //允許來自用戶端的HTML GET請求 json.Data = new { code = 0, message = "成功" }; return json; //這裡直接返回一個json對象給用戶端,用戶端通過ajax的請求後,獲得的直接就是一個json對象,不需要再用$.parseJSON(data)這個方式將字串轉換成Json對象了,因為取到的本身就是一個json對象,而不是一個字串。 } //---------------------------------第二種寫法:伺服器返回一個Json對象 public ActionResult GetData2() { //其實調用的是JsonResult類下的這個方法:protected internal JsonResult Json(object data); //注意:Json()是一個方法,參數是一個object類型的對象,傳回值是JsonResult類型 return Json(new { code = 0, message = "ON" }); //通過測試:採用這種形式,用戶端只能通過非同步Post請求才能取到資料,如果非同步Get請求,無法擷取資料 } //---------------------------------第三種寫法:伺服器返回一個Json格式的字串 public ActionResult GetData3() { JavaScriptSerializer json = new JavaScriptSerializer(); var jsonObj = new { code = 1, message = "OK" }; //構造一個對象 string jsonStr = json.Serialize(jsonObj); //將這個對象轉換成json格式的字串 return Content(jsonStr); //返回一個json格式的字串。 所以用戶端通過ajax請求後,獲得的這個資料僅僅是一個json格式的字串,所以需要用$.parseJSON(data)這個方式將字串轉換成Json對象 } }}
視圖 View
<html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/jquery-1.11.2.js"></script></head><body> <div> <button id="submit1">提交1</button> <button id="submit2">提交2</button><button id="submit3">提交3</button> </div></body></html><script type="text/javascript"> $(function () { $("#submit1").click(function () { $.get("/Home/GetData1", function (data) { //伺服器端返回的是一個Json對象,所以這個data是一個json對象,並不是一個json格式的字串。 alert(data.code); //列印出:0 alert(data.message);//列印出:成功 //除了以上的取值方式外下面的方式也是可以取到值的 alert(data["code"]); //列印出:0 alert(data["message"]); //列印出:成功 }) }) })</script><script type="text/javascript"> $(function () { $("#submit2").click(function () { //不知道為什麼這種一定要是非同步Post請求,如果是非同步Get請求無法取到資料 $.post("/Home/GetData2", function (data) { //伺服器端返回的是一個Json對象,所以這個data是一個json對象,並不是一個json格式的字串。 alert(data.code); //列印出:0 alert(data.message); //列印出:ON }) }) })</script><script type="text/javascript"> $(function () { $("#submit3").click(function () { $.get("/Home/GetData3", function (data) { //伺服器返回的是一個json格式的字串,所以這個data是一個字串,並不是一個對象 var jsonObj = $.parseJSON(data); //將這個字串 轉換成json對象 alert(jsonObj.code); //列印出:1 alert(jsonObj.message); //列印出:OK }) }) })</script>
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。