JSON的使用案例
json就是用来前后端传输数据的
1.需要导包
2.后端Servlet的简单代码
int pid = Integer.parseInt(request.getParameter("pid"));
CityDao dao = new CityDaoImp();
List<CityBean> list = dao.findCity(pid);
JSONArray jsonArray = JSONArray.fromObject(list);
String json = jsonArray.toString();
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
3.前端的JavaScript代码
$(function(){
$("#province").change(function(){
var pid = $(this).val();
//先清空
$("#city").html("<option value=''>-请选择-")
$.post("CityServlet",{pid:pid},function(data,status){
$(data).each(function(index,c){
$("#city").append("<option value='"+c.id+"'>"+c.name);
});
},"json");
});
});
post的方法发送到服务器然后调用function