前臺(tái)Ajax請(qǐng)求很多時(shí)候需要從后臺(tái)獲取JSON格式數(shù)據(jù),一般有以下方式:
拼接字符串
1
|
return Content( "{\"id\":\"1\",\"name\":\"A\"}" ); |
為了嚴(yán)格符合Json數(shù)據(jù)格式,對(duì)雙引號(hào)進(jìn)行了轉(zhuǎn)義。
使用JavaScriptSerialize.Serialize()方法將對(duì)象序列化為JSON格式的字符串 MSDN
例如我們有一個(gè)匿名對(duì)象:
1
2
3
4
5
|
var tempObj= new { id=1, name= "A" } |
通過(guò)Serialize()方法,返回Json字符串:
1
2
|
string jsonData= new JavaScriptSerializer().Serialize(tempObj); return Content(jsonData); |
返回JsonResult類型 MSDN
ASP.NET MVC 中,可以直接返回序列化的JSON對(duì)象:
1
2
3
4
5
6
7
8
9
10
|
public JsonResult Index() { var tempObj= new { id=1, name= "A" } return Json(tempObj, JsonRequestBehavior.AllowGet); } |
需要設(shè)置參數(shù)‘JsonRequestBehavior.AllowGet',允許GET請(qǐng)求。
前臺(tái)處理返回的數(shù)據(jù)時(shí),對(duì)于1,2種方法,需要使用JQuery提供的parseJSON方法,將返回的字符串轉(zhuǎn)換為JSON對(duì)象:
1
2
3
4
5
6
7
|
$.ajax({ url: '/home/index' , success: function (data){ var result=$.parseJSON(data); //... } }); |
對(duì)于第三種方法,直接作為JSON對(duì)象使用即可。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/luotaoyeah/p/3325264.html