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