//getNationList.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=utf-8");
String[] nationList = {
"汉族", "蒙古族", "回族", "藏族", "维吾尔族", "苗族", "彝族", "壮族", "布依族", "朝鲜族",
"满族", "侗族", "瑶族", "白族", "土家族", "哈尼族", "哈萨克族", "傣族", "黎族", "僳僳族",
"佤族", "畲族", "高山族", "拉祜族", "水族", "东乡族", "纳西族", "景颇族", "柯尔克孜族", "土族",
"达斡尔族", "仫佬族", "羌族", "布朗族", "撒拉族", "毛南族", "仡佬族", "锡伯族", "阿昌族", "普米族",
"塔吉克族", "怒族", "乌孜别克族", "俄罗斯族", "鄂温克族", "德昂族", "保安族", "裕固族", "京族", "塔塔尔族",
"独龙族", "鄂伦春族", "赫哲族", "门巴族", "珞巴族", "基诺族"
};
JSONObject jsonObj = new JSONObject();
jsonObj.put("list", nationList);
JSONArray jsonArr = new JSONArray();
jsonArr.add(jsonObj);
response.getWriter().print(jsonArr.toString());
}
//register.js
//获取XMLHttpRequest对象
function createXMLHttpRequest() {
var xmlHttpRequest = null;
if(window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlHttpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
// IE6, IE5 浏览器执行代码
try {
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHttp");
} catch(e) {
try {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
} catch(e2) {
throw new Error("当前浏览器无法创建XMLHttpRequest对象.");
}
}
}
return xmlHttpRequest;
}
//Ajax请求
function sendRequest(url, params, method, handle) {
var xmlHttpRequest = createXMLHttpRequest();
if(!xmlHttpRequest) {
return false;
}
xmlHttpRequest.onreadystatechange = function() {
//JSONArray转化为Array对象
var nationList = JSON.parse(xmlHttpRequest.responseText)[0].list;
handle(nationList);
};
if(method == "GET" || method == "get") {
xmlHttpRequest.open(method, url, true);
xmlHttpRequest.send(null);
} else if(method == "POST" || method == "post") {
xmlHttpRequest.open(method, url, true);
xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpRequest.send(params);
}
};
function getNationList() {
sendRequest("servlet/GetNationList", null, "GET", function(nationList) {
//获取民族列表
var list = document.getElementById("list");
//添加select下拉选项
for(var i = 0; i < nationList.length; i++) {
list.options.add(new Option(nationList[i], nationList[i]));
}
});
}
Servlet和Ajax传递JSON
最新推荐文章于 2021-10-05 11:24:42 发布