1、在Eclipse中创建项目目录视图如下:
2、代码及注解如下
{"person":{ "name":"Hello Andy","website":"http://www.test001.com/","email":"andy@qq.com" } }
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>AJAX--数据格式--JSON</title> <script type="text/javascript"> window.onload = function() { var aNodes = document.getElementsByTagName('a'); for (var i = 0; i < aNodes.length; i++) { aNodes[i].onclick = function() { // 创建XMLHttpRequest对象 var request = new XMLHttpRequest(); var method = "GET"; var url = this.href; // 调用Open方法 request.open(method,url); // 调用send方法 request.send(null); request.onreadystatechange = function() { if (request.readyState == 4) { if (request.status == 200 || request.status == 304) { // 1、结果是JSON格式,使用responseText来获取 var result = request.responseText; // 使用eval()函数将一个字符串转为本地的JSON来执行 var object = eval("(" + result + ")"); var Tname = object.person.name; var Twebsite = object.person.website; var Temail = object.person.email; // 创建第一个<a>节点 var aNode = document.createElement('a'); aNode.appendChild(document.createTextNode(Tname)); aNode.href = "mailto:" + Temail; // 创建<h2>标签 var h2Node = document.createElement('h2'); h2Node.appendChild(aNode); // 创建第2个<a>标签 var aNode2 = document.createElement('a'); aNode2.appendChild(document.createTextNode(Twebsite)); aNode2.href = Twebsite; // 4、将拼写得到的JSON数据信息添加到"id = 'detail'"中 var detailNode = document.getElementById('detail'); // 清空detailNode中的数据 detailNode.innerHTML = ""; detailNode.appendChild(h2Node); detailNode.appendChild(aNode2); } } } return false; } // aNodes[i].onClick = function() } // for (var i = 0; i < aNodes.length; i++) } // window.onload = function() </script> </head> <body> <h2>Person</h2> <ul> <li><a href="files/andy.js">First andy</a></li> <li><a href="files/jeremy.js">Second jeremy</a></li> <li><a href="files/richard.js">Third richard</a></li> </ul> <div id="detail"></div> </body> </html>
3、运行结果如下所示:
--------------------------------------------------------------------------------------------------------------------------------------------
JSON代码小练习--testjson.html
<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <title>JSON小练习</title> <script type="text/javascript"> var jsonObject = { "name":"Bob","age":"12","address":{"city":"BeiJing","school":"大中华"},"teaching" : function() { alert("JavaEE,Android..."); } }; /* alert(jsonObject.name); alert(jsonObject.address.city); jsonObject.teaching(); */ var jsonStr = "{'name':'Tom'}"; // 把一个字符串转换为JSON对象! //alert(jsonStr.name); // 返回结果为: undefined // 使用eval()方法 var testStr = "alert('hello eval')"; // alert(testStr); // eval()可以把一个字符串转为本地的JS代码来执行 eval(testStr); // 返回结果:hello eval // eval()函数把jsonStr字符串转换为JSON对象 var testObject = eval("(" + jsonStr + ")"); alert(testObject.name); </script> </head> <body> </body> </html>原文链接:https://www.f2er.com/ajax/160611.html