现在的位置: 首页 > 综合 > 正文

struts2 读取json数据

2013年08月31日 ⁄ 综合 ⁄ 共 1344字 ⁄ 字号 评论关闭

一 json数据 创建json 文本json.txt

  1. {   
  2.      userName: "nihao",   
  3.      sex: "male",   
  4.      age: "23"  
  5. }  

二 创建Ajax请求

  1. function createXMLHttpRequest() {   
  2.     var req;   
  3.          if (window.XMLHttpRequest) {   
  4.         req = new XMLHttpRequest();   
  5.     }else if (window.ActiveXObject) {   
  6.         req = new ActiveXObject("Microsoft.XMLHTTP");   
  7.     }   
  8.     return req;   
  9. }  

三 页面异步读取json

  1. <script type="text/javascript">   
  2.         var req = createXMLHttpRequest();   
  3.         function startRequest(){   
  4.             try{   
  5.                 req.onreadystatechange = handleStateChange;   
  6.                 req.open("GET""json.txt"true);   
  7.                 req.send(null);       
  8.             }catch(exception){   
  9.                 alert("");   
  10.             }     
  11.         }   
  12.         function handleStateChange(){       
  13.             if(req.readyState == 4){           
  14.                  if (req.status == 200 || req.status == 0){   
  15.                     // 取得返回字符串   
  16.                     var resp = req.responseText;   
  17.                     // 构造返回JSON对象的方法   
  18.                     var func = new Function("return " + resp);   
  19.                     // 得到JSON对象   
  20.                     var json = func( );   
  21.                     // 显示返回结果   
  22.                     alert("userName: " + json.userName + " " + "sex: " + json.sex + " " + "age: " + json.age);   
  23.                   }   
  24.              }   
  25.          }         
  26.     </script>   

 

 

抱歉!评论已关闭.