JS传递数组到后台

方法一:

1.使用JSON.stringify 将数组对象转化成json字符串;

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',  
    contentType : "application/json" ,
    data : JSON.stringify(array), 
    success : function(data) {  

    }  
}); 

2.传输过程中参数

Request Payload
    ↓["1","2"]
        0:"1"
        1:"2"

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(@RequestBody String[] array) throws IOException {
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}

4.前台传字符串数组

 var str = "";
            $("#myModal input[type='checkbox']").each(function(){
                if($(this).is(":checked"))
                {
                    str +=$(this).val()+',';
                }
            });
var url = $("#path").val() + "/rest?orgId=" + orgId + "&columnsTable=" + str;

5.后台接收

@RequestParam("columnsTable") String[] columnsTable
//4,3,2,1,0
方法二:

1.前端不做处理:

var array = ["1", "2"];
$.ajax({  
    type : 'POST',  
    url: path + '/check/testPost',
    contentType: "application/x-www-form-urlencoded",
    data: {"array": array},
    success : function(data) {  
    }  
});  

2.传输过程中参数

Form Data
    array[]:1
    array[]:2

3.后台处理

@RequestMapping(value = "/testPost", method = {RequestMethod.POST})
public void testPost(HttpServletRequest req) throws IOException {
    String[] array = req.getParameterValues("array[]");
    for (String string : array) {
        System.out.println(string);
    }
    return ;
}

注:两种post请求的content-type不同。

这里是一个真诚的***青年技术交流QQ群:761374713***,不管你是大学生、社畜、想学习变成的其他人员,欢迎大家加入我们,一起成长,一起进步,真诚的欢迎你,不管是技术,还是人生,还是学习方法。有道无术,术亦可求,有术无道,止于术。在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值