通常ajax请求返回的格式为json或者xml,如果返回的是json,则可以通过转换成javascript对象进行操作,如下:
1、ajax请求的controller实现
@RequestMapping public void getLocations(@RequestParam String location, PrintWriter printWriter) { if (StringUtils.isEmpty(location)) { return; } List<Location> locations = locationService.getSubLocation(location); String json = Json.toJson(locations); printWriter.write(json); printWriter.flush(); printWriter.close(); }
Location是包含多个属性的Bean,如pName、zName。
2、ajax处理请求与返回值
$.ajax({ type : "GET", url : "/admin/location/getLocations.do", data : "location=" + val, success : function(msg) { msg = eval(msg); region = $("#region"); region.empty(); vHtml = "<option value='none'>选择区(可选)</option>"; $.each(msg, function(i) { var $bean = msg[i]; vHtml += '<option value="' + $bean.pName + '"">' + $bean.zName + '</option>'; }); region.html(vHtml); } });
msg本来是一个json字符串,使用eval函数将字符串转成了javascript对象,从而可以像对象那样获取属性值了。