转自:http://blog.csdn.net/u011955534/article/details/15942181
1、创建一个json.txt文件
- {
- "programmers": [
- { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
- { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
- { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
- ],
- "authors": [
- { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
- { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
- { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
- ],
- "musicians": [
- { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
- { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
- ]
- }
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <script type="text/javascript">
- var xmlHttp=null;
- //创建xmlhttprequest对象
- if(window.XMLHttpRequest){
- xmlHttp=new XMLHttpRequest();
- }else{
- xmlHttp=new ActiveObject("Microsoft.XMLHTTP");
- }
- function myclick(){
- try{
- xmlHttp.onreadystatechange=handleStateChange;
- xmlHttp.open("get","json.txt",true);
- xmlHttp.send();
- }
- catch(exception){
- alert("xmlHttp fail");
- }
- }
- function handleStateChange(){
- if(xmlHttp.readyState==4 && xmlHttp.status==200){
- var result=xmlHttp.responseText;
- var json=eval("("+result+")");
- alert(json.programmers[0].firstName);
- }
- }
- </script>
- </head>
- <body>
- <div>
- <input type="button" value="AjaxTest" onclick="myclick()"/>
- </div>
- </body>
- </html>