Javascript 和Jquery 通过ID 获取值。
<script> var txt1 = [{ "CityId": 18, "CityName": "西安", "ProvinceId": 27, "CityOrder": 1 }, { "CityId": 53, "CityName": "广州", "ProvinceId": 27, "CityOrder": 1 }]; $("#a1").html(txt1[0].CityName); document.getElementById("a1").innerHTML = txt1[0].CityName; //以上两种写法结果都一样。通过Id 获取值。 </script> <body> <p> 城市:<span id="a1"></span><br /> </p> </body>
Json 对象处理:
<script>
var j1 = { "firstName": "John", "lastName": "Doe" }; var j11 = j1.firstName; alert(j11);
</script>
Json数组:
<script> var aa1 = { "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }; $("#a1").html(aa1.employees[1].firstName); $("#a2").html(aa1.employees[1].lastName); </script> <body> <p> 编号:<span id="a1"></span><br /> 姓名:<span id="a2"></span><br/> </p> </body>
Json 字符串:
由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 eval() 可用于将 JSON 文本转换为 JavaScript 对象。
eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误:
<script> var txt = '{ "employees" : [' + '{ "firstName":"Bill" , "lastName":"Gates" },' + '{ "firstName":"George" , "lastName":"Bush" },' + '{ "firstName":"Thomas" , "lastName":"Carter" } ]}'; var jtxt = eval("(" + txt + ")"); ; $("#a1").html(jtxt.employees[1].firstName); $("#a2").html(jtxt.employees[1].lastName); </script> <body> <p> 编号:<span id="a1"></span><br /> 姓名:<span id="a2"></span><br/> </p> </body>