Ajax核心知识(2)
发布时间:2020-12-16 02:59:56 所属栏目:百科 来源:网络整理
导读:对于Ajax核心的东西需要在进行总结提炼一下: xmlHttp对象。 方法:xml.responseText获取后台传递到前台的数据,经常性的使用var object=xml.responseText; 前端: 二级联动的例子: 1 function onloadInfo(){ 2 var shengId=document.getElementById("sheng
对于Ajax核心的东西需要在进行总结提炼一下: xmlHttp对象。 方法:xml.responseText获取后台传递到前台的数据,经常性的使用var object=xml.responseText; 前端: 二级联动的例子: 1 function onloadInfo(){ 2 var shengId=document.getElementById("sheng").value; 3 shi.options.length=0;//清除市的下拉框内容! 4 var xmlHttp; 5 if(window.XMLHttpRequest){ 6 xmlHttp=new XMLHttpRequest(); 7 }else{ 8 xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP "); 9 } 10 alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status); 11 xmlHttp.onreadystatechange=function(){ 12 if(xmlHttp.readyState==4&&xmlHttp.status==200){ 13 alert(xmlHttp.responseText); 14 var object=eval("("+xmlHttp.responseText+")"); 15 for(var i=0;i<object.rows.length;i++){ 16 var o=object.rows[i]; 17 shi.options.add(new Option(o.text,o.id)); 18 } 19 } 20 }; 21 xmlHttp.open("get","checkUserName?action=ejld&shengId="+shengId,true); 22 xmlHttp.send(); 23 } 24 </script> 25 <body> 26 <div> 27 省:<select id="sheng" onchange="onloadInfo()"> 28 <option value="1">山东省</option> 29 <option value="2">江苏省</option> 30 <option value="3">宁夏回族自治区</option> 31 </select> 32 市:<select id="shi"> 33 </select> 34 </div> 35 </body> 36 </html> 后台: 1 private void ejld(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { 2 response.setContentType("text/Html;charset=utf-8"); 3 PrintWriter out=response.getWriter(); 4 JSONObject resultJson=new JSONObject(); 5 String shengId=request.getParameter("shengId"); 6 JSONArray Jsonarray=new JSONArray(); 7 JSONObject temp=null; 8 switch(Integer.parseInt(shengId)){ 9 case 1:{ 10 temp=new JSONObject();temp.put("id",1);temp.put("text","济南市");Jsonarray.add(temp); 11 temp=new JSONObject();temp.put("id",2);temp.put("text","潍坊市");Jsonarray.add(temp); 12 temp=new JSONObject();temp.put("id",3);temp.put("text","青岛市");Jsonarray.add(temp); 13 break; 14 } 15 case 2:{ 16 temp=new JSONObject();temp.put("id",4);temp.put("text","南通市");Jsonarray.add(temp); 17 temp=new JSONObject();temp.put("id",5);temp.put("text","苏州市");Jsonarray.add(temp); 18 temp=new JSONObject();temp.put("id",6);temp.put("text","泰兴市");Jsonarray.add(temp); 19 break; 20 } 21 case 3:{ 22 temp=new JSONObject();temp.put("id",7);temp.put("text","银川市");Jsonarray.add(temp); 23 temp=new JSONObject();temp.put("id",8);temp.put("text","吴忠市");Jsonarray.add(temp); 24 temp=new JSONObject();temp.put("id",9);temp.put("text","中卫市");Jsonarray.add(temp); 25 break; 26 } 27 } 28 resultJson.put("rows",Jsonarray); 29 out.println(resultJson); 30 out.flush(); 31 out.close(); 32 } 其中: 对于JSONObject resultJson=new JSONObject(); 我们是一个大的对象里面有一个数组:JSONArray jsonArray=new JSONArray();然后还可以继续往里面加对象。这里面的对象可以有自己的key-value值!这很有意思! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |