废话少说,上代码:
jsp:
function showCreateCrate(cabinetId){
$('#crateBox').html('');
var url = "findContainerBoxList.action";
$.ajax({
url: url,
type:"post",
dataType:"json",
contentType: "application/x-www-form-urlencoded",
data:{cabinetId:cabinetId},
async : false,
success: function (data) {
if(data.msg == "success"){
var jsonStr = data.obj;
var containerBoxList = data.result.containerBoxList;
for(var i=0; i<jsonStr.length;i++){
createCrate(jsonStr[i],containerBoxList[i]);
$('#crateBox').append(newCrate);
}
boardFigureLoad();
}
}
});
}
后台action:
public void findContainerBoxList() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
ResponseVO resVO = new ResponseVO();
Map<String,Object> map = new HashMap<String,Object>();
containerBoxList = collectorService.getBoxListByCabinet(cabinetId);
if(containerBoxList!=null){
cardBoardListByBox = collectorService.getCardBoardListsByBox(containerBoxList);
resVO.setObj(cardBoardListByBox);
}else {
cardBoardListByBox = null;
resVO.setObj(new Object());
}
map.put("containerBoxList",containerBoxList);
resVO.setResult(map);
resVO.setMsg("success");
response.getWriter().write(JSONObject.fromObject(resVO).toString());
}
后台返回JSON给前端的代码就是action中的最后一步。
关于所有代码都运行正确,但前端却不进入success的问题,原因是前后端的数据类型不一致,
解决方法就是把数据类型统一:
ajax中:
dataType:”json”,
action中:
response.setContentType(“application/json;charset=UTF-8”);
response.getWriter().write(JSONObject.fromObject(resVO).toString());
注意最后一行是 JSONObject.fromObject,不是JSONArray.fromObject