jQuery 使用ajax将数组数据从浏览器中的javascript传递到spring mvc控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17560258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:18:27  来源:igfitidea点击:

Pass array data from javascript in browser to spring mvc controller using ajax

javascriptjqueryajaxarraysspring-mvc

提问by Alfred Zhong

I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX

我想使用 AJAX 将 Web 浏览器中的 javascript 数组传递给 Spring MVC 控制器

In javascript, I have

在javascript中,我有

var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;

// how about multiple arrays as well?

$.ajax({
    type : "POST",
    url : "/myurl",
    data : //not sure how to write this, ("a="+a), ?
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

In Java, I would like to create a class to receive data from AJAX, and I create a class to receive data

在Java中,我想创建一个类来接收来自AJAX的数据,我创建了一个类来接收数据

package com.amazon.infratool.ui;

import lombok.Getter;
import lombok.Setter;


@Setter @Getter
public class RepairInfomationParameters {
//how to write this variable?
    List<String> a = null; // is it something like this?
}

What is the correct way to do this? Thanks!

这样做的正确方法是什么?谢谢!

回答by Vivin Paliath

You can do this from the JavaScript side:

您可以从 JavaScript 端执行此操作:

$.ajax({
    type : "POST",
    url : "/myurl",
    data : {
        myArray: a //notice that "myArray" matches the value for @RequestParam
                   //on the Java side
    },
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

Then on the Java side (in Spring 3), assuming that this method is mapped by /myurl:

然后在 Java 端(在 Spring 3 中),假设这个方法被映射为/myurl

public String controllerMethod(@RequestParam(value="myArray[]") Integer[] myArray){
    ....
}

I believe the following will also work:

我相信以下内容也将起作用:

public String controllerMethod(@RequestParam(value="myArray[]") List<Integer> myArray){
    ....
}

Spring is smart enough to figure out how to do the binding.

Spring 足够聪明,可以弄清楚如何进行绑定。

For multiple arrays, you might want to just have a command object:

对于多个数组,您可能只想拥有一个命令对象:

public class MyData {
    private List<Integer> firstArray;
    private List<Integer> secondArray;
    private List<Integer> thirdArray;

    ...
    ...
}

Then on the JavaScript side:

然后在 JavaScript 方面:

$.ajax({
    type : "POST",
    url : "/myurl",
    data : {            
        myData: {
           "firstArray": firstArray,
           "secondArray": secondArray,
           "thirdArray": thirdArray
        }            
    },
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

On the Java side, you can bind using @ModelAttribute:

在 Java 方面,您可以使用@ModelAttribute以下方法进行绑定:

public String controllerMethod(@ModelAttribute(value="myData") MyData myData) throws ParseException {
    ....
}

EDIT

编辑

Changed the @RequestParamannotation to use myArray[]instead of just myArray, since this change appears to have been made in Spring after this answer was first posted.

@RequestParam注释更改为 usemyArray[]而不是 just myArray,因为此更改似乎是在首次发布此答案后在 Spring 中进行的。

回答by a.valchev

It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. So if you want to get an array/list in the controller - pass a stringified version of the array:

当您记住数据是从字符串解析时,将此类数据传递给 Spring MVC 控制器非常简单。因此,如果您想在控制器中获取数组/列表 - 传递数组的字符串化版本:

public String method(
        @RequestParam(value = "stringParam") String stringParam,
        @RequestParam(value = "arrayParam") List<String> arrayParam) {
    ...
}

and the corresponding javascript with jQuery would be like:

和 jQuery 相应的 javascript 会像:

$.post("/urlToControllerMethod",
    {
        "stringParam" : "test",
        "arrayParam" : [1, 2, 3, "test"].toString()
    }
);

Note:the parameter type

注:参数类型

List<String> arrayParam

could be as well replaced with the array equivalent

也可以用等效的数组替换

String[] arrayParam

回答by redochka

Vivin Paliath doesn't work unless you use myArray[]

除非你使用 Vivin Paliath,否则它不起作用 myArray[]

public String controllerMethod(@RequestParam(value="myArray[]") Integer[] myArray){
    ...
}

回答by Chetan Aher

If you are using spring mvc 4 then below will be the best approach

如果您使用的是 spring mvc 4 那么下面将是最好的方法

Jquery code

查询代码

var dataArrayToSend = []; dataArrayToSend.push("a"); dataArrayToSend.push("b"); dataArrayToSend.push("c");

var dataArrayToSend = []; dataArrayToSend.push("a"); dataArrayToSend.push("b"); dataArrayToSend.push("c");

// ajax code

// ajax代码

$.ajax({ contentType: "application/json", type: "POST", data: JSON.stringify(dataArrayToSend), url: "/appUrl", success: function(data) { console.log('done'); }, error: function(jqXHR, textStatus, errorThrown) { console.log('error while post'); }
});

$.ajax({ contentType: "application/json", type: "POST", data: JSON.stringify(dataArrayToSend), url: "/appUrl", success: function(data) { console.log('done'); }, error: function(jqXHR, textStatus, errorThrown) { console.log('error while post'); }
});

Spring controller code

弹簧控制器代码

@RequestMapping(value = "/appUrl", method = RequestMethod.POST) public @ResponseBody void yourMethod(@RequestBody String[] dataArrayToSend) { for (String data : dataArrayToSend) { System.out.println("Your Data =>" + data); } }

@RequestMapping(value = "/appUrl", method = RequestMethod.POST) public @ResponseBody void yourMethod(@RequestBody String[] dataArrayToSend) { for (String data : dataArrayToSend) { System.out.println("Your Data =>" + data); } }

check this helps you or not!

检查这是否对您有帮助!

Cheers!

干杯!

回答by Vikas Jain

Fully tested solution

经过全面测试的解决方案

$.ajax({
    type : "POST",
    url : "/myurl",
    data : {
        myArray: a //notice that "myArray" matches the value for @RequestParam
                   //on the Java side
    },
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

@RequestMapping(value = "/save/", method = RequestMethod.POST)
    public String controllerMethod(@RequestParam(value="myArray[]") List<Integer> myArray){
        System.out.println("My Array"+myArray.get(0));
        return "";
    }

回答by Alfred Zhong

I end up doing this and it works

我最终这样做并且它有效

In js,

在js中,

var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;


$.ajax({
    type : "POST",
    url : "/myurl",
    data : "a="+a,  //multiple array, just add something like "&b="+b ...
    success : function(response) {
       // do something ... 
    },
    error : function(e) {
       alert('Error: ' + e);
    }
}); 

java side, get a class to receive data, using lombok

java端,获取一个类来接收数据,使用lombok

@Setter @Getter public class MyData { private ArrayList a;
}

@Setter @Getter public class MyData { private ArrayList a;
}

then in the controller

然后在控制器中

@RequestMapping(value = "/repair_info", method = RequestMethod.POST)
public ModelAndView myControl(MyData myData) {
    // get data with myData object
}