action如何返回JSON数据,以及返回成功为什么不进入前端ajax的success的问题

废话少说,上代码:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值