Javascript 如何在 Ajax 中发送 js 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8265717/
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-24 05:22:21  来源:igfitidea点击:

How to send js array in Ajax

javascriptjsonjqueryspring-mvc

提问by Vivek

I have created a JS array like this var detailsArr = new Array();and pushing some data into this array.

我已经创建了一个这样的 JS 数组var detailsArr = new Array();并将一些数据推送到这个数组中。

Now i push this array via Ajax to my Spring Controller like this

现在我通过 Ajax 将这个数组推送到我的 Spring Controller 中

$.ajax({
            type: "POST",
            url: "submit",
            data: ({detailsArr : detailsArr }),
            success: function(html){
              alert( "Submitted");
                }
          });

At the Spring Controller side , i receive this array through the @RequestBodyannotation. The Spring Controller method signature looks like this

在 Spring Controller 端,我通过@RequestBody注释接收到这个数组。Spring Controller 方法签名如下所示

public String submit(@RequestBody String body) 

But the array when received at the Spring Controller side is basically a String of this format

但是在Spring Controller端接收到的数组基本上是这种格式的String

detailsArr[]=add&detailsArr[]=test1&detailsArr[]=test2&detailsArr[]=test3

I have to manually split this String to get the values, this is a cumbersome process. Is there any way in which I can get the array as it is , so that I just have to iterate over it to get the values.

我必须手动拆分此字符串才能获取值,这是一个繁琐的过程。有什么方法可以按原样获取数组,以便我只需遍历它即可获取值。

采纳答案by erimerturk

you should pass your array to server in json format. And convert it by using Json to object converter. you can use Gson.

您应该以 json 格式将数组传递给服务器。并使用 Json 将其转换为对象转换器。你可以使用Gson.

client side:

客户端:

$.ajax({
            type: "POST",
            url: "submit",
            data:JSON.stringify(detailsArr),
            success: function(html){
              alert( "Submitted");
                }
          });

server side :

服务器端 :

public String submit(@RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}

回答by xbonez

When passing it to your controller, pass it like this:

将它传递给您的控制器时,请像这样传递它:

data:JSON.stringify(detailsArr);

At your controller, you can then decode the JSON received.

在您的控制器上,您可以解码收到的 JSON。