Servlet和Ajax传递JSON

//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]));
        }
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值