如何在Ajax中发送js数组 [英] How to send js array in Ajax

查看:85
本文介绍了如何在Ajax中发送js数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

现在我将这个数组通过Ajax推送到我的Spring Controller,就像这样

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

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

在Spring Controller端,我通过 @RequestBody <接收此数组/ code>注释。 Spring Controller方法签名看起来像这样

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

public String submit(@RequestBody String body) 

但是在Spring Controller端收到的数组基本上是这种格式的字符串

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

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

我必须手动拆分此String以获取值,这是一个繁琐的过程。有没有什么方法可以让我得到数组,所以我只需要迭代它来获取值。

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.

推荐答案

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

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

客户端:

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

服务器端:

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

这篇关于如何在Ajax中发送js数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆