ajax上传JSON格式的多维数组的方法_ajax 提交多维json数据

首先是伟大的接口文档
这里写图片描述
解析json可以看到

{
    "name":"收货人",
    "phone":"15101586519",
    "address":"收货地址",
    "send_integral":0,
    "invoice_type":"3",
    "invoice_detail":"hjfyjjhkl45745",
    "invoice_raise_head":"发票抬头",
    "user_id":"31",
    "cart_id":"14",
    "info":[
        {
            "supply_id":"3",
            "goods":[
                {
                    "anchor_id":"20",
                    "commodity_id":"2",
                    "number":"1"
                },
                {
                    "anchor_id":"20",
                    "commodity_id":"3",
                    "number":"1"
                },
                {
                    "anchor_id":"20",
                    "commodity_id":"4",
                    "number":"1"
                },
                {
                    "anchor_id":"20",
                    "commodity_id":"5",
                    "number":"1"
                },
                {
                    "anchor_id":"20",
                    "commodity_id":"6",
                    "number":"1"
                }
            ],
            "remarks":"备注"
        },
        {
            "supply_id":"3",
            "goods":Array[5],
            "remarks":"备注"
        }
    ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

请求的参数看起来很多,实际上只有一个order,而且是string的参数类型。
所以,可以直接创建一个order如下
var order={
name:$("#name").text(),
phone:$("#phone").text(),
address:$("#address").text(),
send_integral:integral,
invoice_type:type,
invoice_raise_head:$("#billName").val(),
invoice_detail:$("#billNum").val(),
user_id:sessionStorage.getItem("id"),
cart_id:carid.join(","),
info:infoArr
};

注:infoArr是一个数组。
然后ajax直接进行上传

                    $.ajax({
                        type:"post",
                        url:addOrderUrl,
                        data:{
                            order:JSON.stringify(order)//JSON.stringify()转为字符串
                        },
                        async:true,
                        dataType:"json",
                        success:function(data){
                            //成功
                        },
                        error:function(data){
                            //失败
                        }
                    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15