前台Ajax請求很多時候需要從后台獲取JSON格式數據,一般有以下方式:
拼接字符串
return Content("{\"id\":\"1\",\"name\":\"A\"}");
為了嚴格符合Json數據格式,對雙引號進行了轉義。
使用JavaScriptSerialize.Serialize()方法將對象序列化為JSON格式的字符串 MSDN
例如我們有一個匿名對象:
var tempObj=new { id=1, name="A" }
通過Serialize()方法,返回Json字符串:
string jsonData=new JavaScriptSerializer().Serialize(tempObj); return Content(jsonData);
返回JsonResult類型 MSDN
ASP.NET MVC 中,可以直接返回序列化的JSON對象:
public JsonResult Index() { var tempObj=new { id=1, name="A" } return Json(tempObj, JsonRequestBehavior.AllowGet); }
需要設置參數‘JsonRequestBehavior.AllowGet’,允許GET請求。
前台處理返回的數據時,對於1,2種方法,需要使用JQuery提供的parseJSON方法,將返回的字符串轉換為JSON對象:
$.ajax({ url:'/home/index', success:function(data){ var result=$.parseJSON(data); //... } });
對於第三種方法,直接作為JSON對象使用即可。