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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章