首页 > 代码库 > ajax提交复杂对象数据

ajax提交复杂对象数据

public class RouteItemManageReq {
    private List<WorkNodeReq> targetNodes;
    private RouteItemReq obj;
    public List<WorkNodeReq> getTargetNodes() {
        return targetNodes;
    }
    public void setTargetNodes(List<WorkNodeReq> targetNodes) {
        this.targetNodes = targetNodes;
    }
    public RouteItemReq getObj() {
        return obj;
    }
    public void setObj(RouteItemReq obj) {
        this.obj = obj;
    }
}
    public @ResponseBody List<SpiderBaseRespCenterExt> pushAddRouteItem(RouteItemManageReq req,Model model) {
        return nodeManageService.pushAddRouteItem(req);
    }

要在ajax中提交类似这样的结构,不能直接将js直接附加到ajax请求的data上,否则不管是数组还是属性都会以obj[prop][subprop]的方式传递到服务端,导致spring mvc无法解析而报错。

所以,如果在ajax中需要通过拼接成string的方式传递。类似如下:

            for(var x=0;x<targetNodes.length;x++) {
                formData = formData + "targetNodes[" + x + "].clusterName=" + targetNodes[x].split(":")[0] + "&";
                formData = formData + "targetNodes[" + x + "].ip=" + targetNodes[x].split(":")[1] + "&";
                formData = formData + "targetNodes[" + x + "].port=" + targetNodes[x].split(":")[2] + "&";
            }
            formData = formData + "obj.routeItem.serviceId=" + $("#myModal-route input[name=‘serviceId‘]").val() + "&";
            formData = formData + "obj.routeItem.systemId=" + $("#myModal-route input[name=‘systemId‘]").val() + "&";
            formData = formData + "obj.routeItem.subSystemId=" + $("#myModal-route input[name=‘subSystemId‘]").val() + "&";
            formData = formData + "obj.routeItem.appVersion=" + $("#myModal-route input[name=‘appVersion‘]").val() + "&";
            formData = formData + "obj.routeItem.companyId=" + $("#myModal-route input[name=‘companyId‘]").val() + "&";
            formData = formData + "obj.routeItem.clusterName=" + $("#myModal-route input[name=‘clusterName‘]").val();

            $.ajax({
                url: "/middle/00000110.json",    //请求的url地址
                dataType: "json",   //返回格式为json
                // async: false, //请求是否异步,默认为异步,这也是ajax重要特性
                data: formData,    //参数值
                type: "GET",   //请求方式

 

ajax提交复杂对象数据