JSON概述
<!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> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>JSON概述</title> <script type="text/javascript"> /* /* JSON格式的本质 就是 字符串 javascript对象的格式 JS数组格式: var arr = ['a','b','c']; JSON格式1: var arr = "['a','b','c']"; ---------------------------------- JS对象格式: var person = {'name':'张三','age':'15','sex':'男'}; JSON格式2: var person = "{'name':'张三','age':'15','sex':'男'}"; ------------------------------------- JSON的取值 步骤: 1、把JSON字符串用eval函数变成 JavaScript相应的对象 2、应用取值 eval(字符串) 可把字符串变成JavaScript代码解析运行 返回值。 把JavaScript代码解析返回 eval("("+json1+")") 在字符串前加"(" 在字符串后加")" 为了照应浏览器兼容性,可以让JSON数据顺利转成JavaScript对象。必须加括号 var json1 = "['a','b','c']";//json var arr = eval("("+json1+")"); alert(arr.length); for(var x in arr){ alert(arr[x]);} var json2 = "{'name':'张三','age':'15','sex':'男'}"; var arr2 = eval("("+json2+")"); alert(arr2.length); for(var x in arr2){ alert(x+"="+arr2[x]);} */ function run1() { var goodsJ = "[{'name':'电视机','price':'200','number':'10'},{'name':'手机','price':'4200','number':'100'},{'name':'电冰箱','price':'2000','number':'8'}]"; var goods = eval("("+goodsJ+")"); var tableNode = document.getElementById("ii"); alert(tableNode.innerHTML); for(var x=0;x<goods.length;x++) { tableNode.innerHTML+="<tr><td>"+goods[i]["name"]+"</td><td>"+goods[i]["price"]+"</td><td>"+goods[i]["number"]+"</td></tr>"; } } </script> </head> <body> <table border="1" width="100%" id="ii"> <tr> <th>商品名称</th> <th>商品价格</th> <th>商品数量</th> </tr> </table> <input type="button" value="点击获取具体信息" onclick="run1()"/> </body> </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>03JSON案例.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript"> /* JSON的数据是从server拿来的。 */ function run(){ //1、JSON数据是从server拿到的 var goodsJ = "[{'name':'电视机','price':'200','number':'10'},{'name':'手机','price':'4200','number':'100'},{'name':'电冰箱','price':'2000','number':'8'}]"; //2、把JSON数据变成JavaScript对象 var goods = eval("("+goodsJ+")"); //3、(准备)把table对象拿到 var tableNode=document.getElementById("t1"); // alert(tableNode.innerHTML); //4、把获取到的数据进行遍历,而且动态加入进table for(var i=0;i<goods.length;i++){ tableNode.innerHTML+="<tr><td>"+goods[i]["name"]+"</td><td>"+goods[i]["price"]+"</td><td>"+goods[i]["number"]+"</td></tr>"; } } </script> </head> <body> <table border="1" width="100%" id="t1"> <tr> <th>商品名称</th> <th>商品价格</th> <th>库存</th> </tr> </table> <br/> <input type="button" value="点我载入数据" onclick="run()"/> </body> </html>