AJAX读取json数据

转自:http://blog.csdn.net/u011955534/article/details/15942181

1、创建一个json.txt文件

[plain] view plain copy
  1. {    
  2. "programmers": [    
  3. { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },    
  4. { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },    
  5. { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }    
  6. ],    
  7. "authors": [    
  8. { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },    
  9. { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },    
  10. { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }    
  11. ],    
  12. "musicians": [    
  13. { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },    
  14. { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }    
  15. ]    
  16. }  
2、jsp页面
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.   <script type="text/javascript">  
  11.    var xmlHttp=null;  
  12.    //创建xmlhttprequest对象   
  13.   if(window.XMLHttpRequest){  
  14.     xmlHttp=new XMLHttpRequest();  
  15.   }else{  
  16.     xmlHttp=new ActiveObject("Microsoft.XMLHTTP");  
  17.   }  
  18.   function myclick(){  
  19.     try{  
  20.         xmlHttp.onreadystatechange=handleStateChange;  
  21.         xmlHttp.open("get","json.txt",true);  
  22.         xmlHttp.send();  
  23.     }  
  24.     catch(exception){  
  25.         alert("xmlHttp fail");  
  26.     }  
  27.   }  
  28.   function handleStateChange(){  
  29.     if(xmlHttp.readyState==4 && xmlHttp.status==200){  
  30.         var result=xmlHttp.responseText;  
  31.         var json=eval("("+result+")");  
  32.         alert(json.programmers[0].firstName);  
  33.     }  
  34.   }  
  35.     
  36.     
  37.   </script>  
  38.   </head>  
  39.     
  40.   <body>  
  41.   <div>  
  42.     <input type="button" value="AjaxTest" onclick="myclick()"/>  
  43.   </div>  
  44.   </body>  
  45. </html> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值