<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>使用xml格式完成数据的传输</title> <script type="text/javascript"> window.onload = function (){ document.getElementsByTagName("a")[0].onclick = function (){ var request = new XMLHttpRequest(); var url = this.href; var method = "GET"; request.open(method, url); request.send(null); request.onreadystatechange = function (){ if(request.readyState == 4){ if(request.status == 200 || request.status == 304){ //结果为XML格式,需要使用responseXML来获取 var result = request.responseText; var object = eval("("+ result+")"); //结果不能直接使用,必须先创建节点,然后再把节点添加到目标节点中 var name = object.person.name; var age = object.person.age; var phone = object.person.phone; alert("name:"+name+" age:"+age+" phone:"+phone); } } }; //阻止a标签的默认行为 return false; }; }; </script> </head> <style> #div1{ 400px; height:400px; background:#FFAABB; } </style> <body> <a href="json.js" >使用xml格式完成页面数据的传输</a> <div id="div1"></div> </body> </html>
请求的json文件:
{ "person":{ "name":"liuyanmin", "age":"21", "phone":"18888888888" } }