標籤:client idt 通過 port ice pos get device 成功
<>
控制器 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(); } //---------------------------------第一種寫法:server返回一個Json對象 public ActionResult GetData1() { JsonResult json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //同意來自client的HTML GET請求 json.Data = new { code = 0, message = "成功" }; return json; //這裡直接返回一個json對象給client,client通過ajax的請求後,獲得的直接就是一個json對象,不須要再用$.parseJSON(data)這個方式將字串轉換成Json對象了,由於取到的本身就是一個json對象。而不是一個字串。 } //---------------------------------另外一種寫法:server返回一個Json對象 public ActionResult GetData2() { //事實上調用的是JsonResult類下的這種方法:protected internal JsonResult Json(object data); //注意:Json()是一個方法,參數是一個object類型的對象。傳回值是JsonResult類型 return Json(new { code = 0, message = "ON" }); //通過測試:採用這樣的形式。client只能通過非同步Post請求才幹取到資料,假設非同步Get請求,無法擷取資料 } //---------------------------------第三種寫法:server返回一個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格式的字串。 所以client通過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) { //server端返回的是一個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) { //server端返回的是一個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) { //server返回的是一個json格式的字串,所以這個data是一個字串。並非一個對象 var jsonObj = $.parseJSON(data); //將這個字串 轉換成json對象 alert(jsonObj.code); //列印出:1 alert(jsonObj.message); //列印出:OK }) }) })</script>
AJAX MVC server返回Json資料,client擷取Json資料