本文实例讲述了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程序设计有所帮助。