通过ajax将数组或list集合传到后台的方法

一、传数组

前端js:

$(document).on('click', '#sendArr', function () {
	var ids = [];
	for(var i=0; i<10; i++){
		ids.push(i);
	}
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: '/test/test/sendArr',
		data: {ids:ids},
		traditional: true,
		success: function (result) {
			console.log(result)
		},
		error: function(data){
		  alert("操作异常");
		}
	});
});

或者

$(document).on('click', '#sendArr', function () {
	var params = {
		ids:[]
	}
	for(var i = 10; i > 0; i--) {
		params.ids.push(i);
	}
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: '/test/test/sendArr',
		data: params,
		traditional: true,
		success: function (result) {
			console.log(result)
		},
		error: function(data){
		  alert("操作异常");
		}
	});
});

后端:

@PostMapping("/sendArr")
public Map<String,Object> sendArr(String[] ids) {
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("ids", ids);
	return map;
}

二、传list集合

前端js:

$("#sendList").click(function(){
	var ids = [];
	for(var i=0; i<10; i++){
		ids[i] = i;
	}
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: '/test/test/sendList',
		data: JSON.stringify(ids),
		contentType:"application/json",
		success: function (result) {
			console.log(result)
		},
		error: function(data){
		  alert("操作异常");
		}
	});
});

后端:

@PostMapping("/sendList")
public Map<String,Object> sendList(@RequestBody List<String> ids) {
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("ids", ids);
	return map;
}

你可能感兴趣的:(前端)