从JavaScript在浏览器中传递数组数据使用Ajax Spring MVC的控制器数组、控制器、器中、数据

由网友(悲观垃圾)分享简介:我想从JavaScript在Web浏览器中的数组传递给使用AJAX Spring MVC的Controller I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX在Jav...

我想从JavaScript在Web浏览器中的数组传递给使用AJAX Spring MVC的Controller

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

在JavaScript中,我有

In javascript, I have

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

在Java中,我想创建一个类从AJAX接收数据,并创建一个类来接收数据。

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

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!

推荐答案

您可以从JavaScript端做到这一点:

You can do this from the JavaScript side:

$.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);
    }
}); 

然后在Java端(在春季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.

有关多个阵列,你可能想只是有一个命令对象:

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;

    ...
    ...
}

然后在JavaScript端:

Then on the JavaScript side:

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

在Java方面,可以绑定使用 @ModelAttribute

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

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

相关推荐

最新文章