美文网首页
ajax传参数组,spring boot 接收

ajax传参数组,spring boot 接收

作者: 会灰的大飞狼 | 来源:发表于2018-03-30 15:50 被阅读0次

前端:

1.生成数组

function getIds() {
    var info = [];
    $("input[name=checkbox1]:checked").each(function () {
        if ($(this).attr("name") !== "th") {
            info.push($(this).val());
        }
    });
    return info;
}

2.ajax

var info = getIds();
$.ajax({
    url: 'xxx',
    type: 'POST',
    dataType: "json",
    async: false,
    data: {
        'type': 'type',
        'ids': info
    },
    success: function (result) {
        alert(result.message);
    },
    error: function (result) {
        alert(result.message);
    }
});

后台:

@PostMapping("/xxx")
@ResponseBody
public Map<String, Object> xxx(@RequestParam(value = "ids[]") Integer[] ids,@RequestParam String type) {
    xxxx
    return map;
}

用开发者工具查看传递的参数为:


image.png

这里用几个地方要注意:

  1. ajax这里不能加contentType,因为传的不是json
contentType: 'application/json;charset=utf-8',

2.后台接收传递的数组参数名为ids[],所以后台接收不能是下面这个,下面这个参数名是ids.

@RequestParam Integer[] ids

3.后台接收类型Integer[]也可以是String[]或者是List<Integer>List<String>,但是参数名必须对.
4.如果后台接收的参数名想要设置为@RequestParam Integer[] ids,则需要在ajax那里'ids': info要改为'ids': info+'',下面是改了ajax里参数后,传递到后台的参数名,如图.

image.png
5.如果后台接收不到,说明参数有错误,可以用开发者工具查看传递到后台的参数名是什么.

单独传一个数组的情况下也可以这么传:

1.生成数组

function getIds() {
    var info = [];
    $("input[name=checkbox1]:checked").each(function () {
        if ($(this).attr("name") !== "th") {
            info.push($(this).val());
        }
    });
    return info;
}

2.ajax

var info = getIds();
$.ajax({
    url: 'xxx',
    type: 'POST',
    dataType: "json",
    data: JSON.stringify(info),
    contentType: 'application/json;charset=utf-8',
    success: function (result) {
        alert(result.message);
    },
    error: function (result) {
        alert(result.message);
    }
});

3.后台

@PostMapping("/xxx")
@ResponseBody
public Map<String, Object> xxx(@RequestBody Integer[] ids) {
    xxx
    return map;
}

注意的是:
1.这里ajax传参数的时候,用了一个contentType,设置为json.所以data那里需要放的是JSON.stringify(info)

相关文章

网友评论

      本文标题:ajax传参数组,spring boot 接收

      本文链接:https://www.haomeiwen.com/subject/dajicftx.html