AJAX-JSON

public class ServletJSON extends  HttpServlet {
     @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("company", "新东方");
        jsonObject.put("address", "北京");
        int[] deptnos=new int[]{10,20,30};
        String[] dnames=new String[]{"市场部","组织部","文艺部"};
        JSONArray array=new JSONArray();
        for(int i=0;i<deptnos.length;i++){
            JSONObject j=new JSONObject();
            j.put("deptno", deptnos[i]);
            j.put("dname",dnames[i]);
            array.add(j);
        }
        jsonObject.put("depts",array);
        response.getWriter().print(jsonObject);//将数据存入json以文本形式传送
    
    }
}  
      window.onload=function(){
    	  loadJsonData();
      }
      var xmlHttpRequest;
      function loadJsonData(){
    	  xmlHttpRequest=new XMLHttpRequest();//创建对象
    	  xmlHttpRequest.open("post","ServletJson/list");//设置请求方式和路径
    	  xmlHttpRequest.send(null); //传输的参数
    	  xmlHttpRequest.onreadystatechange=function(){//回调函数
    		  if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){//正常响应
    			  var obj=eval("("+xmlHttpRequest.responseText+")");//将文本转换为json数据
    			  document.getElementById("companyDiv").innerHTML=obj.company;//json对象.key
    			  document.getElementById("addressDiv").innerHTML=obj.address;
    			  var selectObj=document.getElementById("depts");
    			  for(var i=0;i<obj.depts.length;i++){//obj.depts:数组
    				  var optionElt=document.createElement("option");
    				  optionElt.setAttribute("value",obj.depts[i].deptno);//设置option元素的属性
    				  optionElt.appendChild(document.createTextNode(obj.depts[i].dname));//追加文本节点
    				  selectObj.appendChild(optionElt);
    			  }
    		  }
    	  }
      }
    

  

posted @ 2017-10-25 08:58  scwyfy  阅读(161)  评论(0编辑  收藏  举报