简体   繁体   English

从浏览器中的javascript传递数组数据到使用ajax弹出mvc控制器

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

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! 谢谢!

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 @RequestParam annotation to use myArray[] instead of just myArray , since this change appears to have been made in Spring after this answer was first posted. 更改@RequestParam注释以使用myArray[]而不仅仅是myArray ,因为此更改似乎是在首次发布此答案后在Spring中进行的。

It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. 将数据传递给Spring MVC控制器非常简单,因为您要记住从字符串中解析数据。 So if you want to get an array/list in the controller - pass a stringified version of the array: 因此,如果您想在控制器中获取数组/列表 - 传递数组的字符串化版本:

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

Vivin Paliath doesn't work unless you use myArray[] 除非你使用myArray[]否则Vivin Paliath不起作用

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

If you are using spring mvc 4 then below will be the best approach 如果您使用的是spring mvc 4,那么下面将是最好的方法

Jquery code Jquery代码

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'); }
});

Spring controller code Spring控制器代码

@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! 干杯!

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
}

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 "";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM