servlet使用ajax+Json的解析和添加

1.如果是普通的json字符串,使用如下:
服务端:(只要ajax的格式正确,那么在servlet中使用out对象的write()方法输出,那么在ajax的success的回调方法中的data参数就是out对象的writer方法中输出的值)
JSONObject jsonArray = new JSONObject();
jsonArray.put(“wuyonghu”, “吴永胡”);
response.setContentType(“application/json; charset=UTF-8”);
// 已经将数据封装为一个JsonObject
PrintWriter out = response.getWriter();
// 将json对象转换为字符串传递到Jsp界面上去
out.write(jsonArray.toString());
out.flush();

前端:
$.ajax({
type : “POST”,
url : “http://localhost:8080/kkPlayer/GetCategoriesServlet“,
dataType : “json”,//此处要设置成jason
success : function(data) {
alert(data.wuyonghu); //输出结果为”吴永胡”
},
error : function() {
alert(“出现了错误”);
}
});

2.如果是JsonArray格式,解析如下:
服务端:

        ArrayList<Kk_songcate> getsongCates = service.getsongCates();
        // 得到了数据,现在将该数据封装为json
        JSONArray jsonArray = new JSONArray();
        JSONObject categoryesJsonObject = new JSONObject();
        for (int i = 0; i < getsongCates.size(); i++) {
            categoryesJsonObject.put("name", getsongCates.get(i)
                    .getCateName());
            jsonArray.add(categoryesJsonObject);
        }

        // JSONObject jsonArray = new JSONObject();
        // jsonArray.put("wuyonghu", "吴永胡");
        response.setContentType("application/json; charset=UTF-8");
        // 已经将数据封装为一个JsonObject
        PrintWriter out = response.getWriter();
        // 将json对象转换为字符串传递到Jsp界面上去
        out.write(jsonArray.toString());
        out.flush();

前端:
$.ajax({
type : “POST”,
url : “http://localhost:8080/kkPlayer/GetCategoriesServlet“,
dataType : “json”,//此处要设置成jason
success : function(data) {
alert(data[0].name);
/* $.each(data, function(key, value) {
alert(value.name);
}); */
},
error : function() {
alert(“出现了错误”);
}
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值