1.前天Jquery 代码
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Index</title> <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnContent").click(function () { $.get('<%: Url.Action("Content") %>', { date: new Date().getTime() }, function (data) { var json = "[\"Name\",18,\"ture\"]"; //数组型json数据 alert(json); //2.访问 json = eval(json) alert(json[0]); //1 alert(json[1] + 1); //2 alert(json[2] && true); //2 var json2 = "[{\"Name\":\"nie.jl\",\"age\":18,\"address\":{\"City\":\"ShangHai\",\"Code\":200030}}]"; //键值对型json数据,通过eval转化时必须是数组。 json2 = eval(json2); alert(json2[0].Name); alert(json2[0].age + 1); alert(json2[0].address.City); var json3 = { "Name": "nie.jl", "age": 18, "address": { "City": "ShangHai", "Code": 200030} }; //键值对型json数据,key为string类型。 alert(json3.Name); alert(json3.age + 1); alert(json3.address.City); alert(data); alert(eval(data)[0]); alert(eval(data)[1] + 1); alert(eval(data)[2] && true); }, "json"); }); }); </script> <script type="text/javascript"> $(function () { $("#btnJson").click(function () { $.get('<%: Url.Action("Json") %>', { date: new Date().getTime() }, function (data) { alert(data.name); }, "json"); $.getJSON('<%: Url.Action("Json") %>', { date: new Date().getTime() }, function (data) { alert(data.name); }) }); }); </script> </head> <body> <div> <button id="btnContent">btnContent</button> <button id="btnJson">btnJson</button> </div> </body> </html>
2.Controller里面的代码
namespace NHibernateSample.Mvc2Web.Controllers { public class AjaxController : Controller { // // GET: /Ajax/ public ActionResult Index() { return View(); } public ActionResult Content() { return Content("[\"Name\",18,\"ture\"]", "text/json");//json内容必须是数组,js 函数eval 转化为json数据。 } class ListItem { public string Value{get;set;} public string Text{get;set;} } public ActionResult Json() { //List<ListItem> list = new List<ListItem>() { //new ListItem() { Value = "1", Text = "VA" } //}; //return this.Json(list, JsonRequestBehavior.AllowGet); var json = new { name = "nie.jl", age = 13 };//true 布尔型 好想不行,直接变成字符串。 return Json(json,JsonRequestBehavior.AllowGet); } } }