AJAX-JSON
阿新 • • 發佈:2017-10-25
var 北京 傳輸 cnblogs node mes rip Coding tno
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); } } } }
AJAX-JSON