本文實例講述了jsp實現將信息放入xml中的方法。分享給大家供大家參考,具體如下:
一、jsp代碼:
省: <select id="province" name="province" onchange="jsSubmit()"> <option value="北京" selected="selected">北京</option> <option value="廣東">廣東</option> <option value="海南">海南</option> </select> 市: <select id="city" name="city"> <option value="北京">北京</option> </select>
二、ajax代碼創建服務器請求代碼不用寫了,寫onchange時候的事件jsSubmit吧:
function jsSubmit() { createXMLHttpRequest(); var province = document.getElementById("province"); //解決客戶端向服務器端傳輸中文亂碼 var uri = "AjaxAction?value=" + encodeURI(encodeURI(province.value)); xmlHttp.open("POST", uri, true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;") xmlHttp.onreadystatechange = processResponse;//回調函數啊! xmlHttp.send(null); }
三、servlet
public class AjaxAction extends HttpServlet { private static final long serialVersionUID = 1L; private static Map<String, String[]> map = new HashMap<String, String[]>(); static { String[] cities1 = { "海口", "瓊海", "三亞" }; String[] cities2 = { "廣州", "珠海", "佛山", "深圳" }; String[] cities3 = { "北京" }; map.put("北京", cities3); map.put("廣東", cities2); map.put("海南", cities1); } st方法{ String province = request.getParameter("value");// 解決客戶端向服務器端傳輸中文亂碼 String proviceCN = URLDecoder.decode(province, "UTF-8"); String[] cities = map.get(proviceCN);//根據傳來的省,查出已經存放進map中對應的市 response.setContentType("text/xml; charset=UTF-8"); StringBuffer buff=new StringBuffer("<citylist>");///准備拼字符串...... for (String city : cities) { buff.append("<city>").append(city) .append("</city>"); } buff.append("</citylist>"); response.getWriter().println(buff.toString());
四、ajax的回調函數
function processResponse() { if(xmlHttp.readyState == 4) { if(xmlHttp.status == 200) { var cities = xmlHttp.responseXML.getElementsByTagName("city"); var displaySelect = document.getElementById("city"); displaySelect.innerHTML = null; for (var i= 0 ;i < cities.length ; i++){ if (i == 0) { var a= xmlHttp.responseXML.getElementsByTagName("city")[i].firstChild.data;//用firstChild方法,其他方法我用text方法不管用~不知道怎麼回事 var op = new Option(a, a, true, true); } else { var a= xmlHttp.responseXML.getElementsByTagName("city")[i].firstChild.data; var op = new Option(a, a); alert(a); } displaySelect.options[i] = op; } } else { window.alert("請求的頁面有異常"); } } }
希望本文所述對大家jsp程序設計有所幫助。