繁体   English   中英

如何将 Json 数组从 ajax 发送到 Spring Controller?

[英]How to send Json array from ajax to spring Controller?

我有一个如下所示的 html 表,我将数据转换为 json 表单并通过 ajax 发送到 spring 控制器。 在 spring 控制器中,我使用@RequestParam Map<String, String>来获取值,但我将整个 json 字符串作为唯一的键。 使用 modelAttribute 我可以实现这一点,但我有不同的场景,所以我不能使用模型类,所以我也想要这些列标题及其值。

<table>
<thead>
<tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
    <td>A1</td>
    <td>A2</td>
    <td></td>
</tr>
<tr>
    <td>B1</td>
    <td>B2</td>
    <td>B3</td>
</tr>
<tr>
    <td>C1</td>
    <td></td>
    <td>C3</td>
</tr>
</tbody>

我将 html 表数据转换为 json 并通过 ajax 发送。 -

  [
    {
    "Column 1": "A1",
    "Column 2": "A2",
    "Column 3": ""
    },
   {
    "Column 1": "B1",
    "Column 2": "B2",
    "Column 3": "B3"
   },
   {
    "Column 1": "C1",
    "Column 2": "",
    "Column 3": "C3"
   }
  ]

ajax代码——

$.ajax({
        type: "POST",
        //contentType : 'application/json; charset=utf-8',
        //dataType : 'json',
        url: "/gDirecotry/" + id,
        data: JSON.stringify(rows),
        success: function (result) {
            console.log(result);
        }
    });

弹簧控制器代码 -

  @RequestMapping(value = "/gDirecotry/{id}", method = RequestMethod.POST)
  public @ResponseBody ModelAndView 
      getSearchUserProfiles(@PathVariable("id") String id,
                                 @RequestParam Map<String, String> 
   attributeMap) throws IOException {

return new ModelAndView("redirect:/home");
  }

我想将 json 数据映射到map<string,string> ,我怎么能做到这一点?

输出: -我将整个字符串作为唯一没有价值的键。

[{"Column 1":"A1","Column 2":"A2","Column 3":""},{"Column 1":"B1","Column 
2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"","Column 3":"C3"}]

更改:

@RequestParam Map<String, String> attributeMap

@RequestBody List<Map<String, String>> attributeMap

JSON有效负载是对象数组。

对象数组的示例。

控制器:

@RequestMapping(value = "alterarSolicitacoesPerfil.do", method = RequestMethod.POST)
@ResponseBody
public Boolean alterarSolicitacoes(@RequestBody SolicitacaoPerfilAcessoRespostaVO[] solicitacoes) throws Exception  {
    List<SolicitacaoPerfilAcessoRespostaVO> listaSolicitacoes = Arrays.asList(solicitacoes);
    controllerService.alterarSolicitacoesPerfilAcesso(listaSolicitacoes);
    return true;
}

阿贾克斯:

alterarSolicitacoes = function (){
var dataArray = new Array();
    
for(var i = 0; i < 10; i++){
 var data = {};
 data.id = i
 data.desc = "teste" 
 dataArray.push(data)
}

    $.ajax({
            type: "POST",
            dataType: 'json',
            contentType: 'application/json', 
            data: JSON.stringify(dataArray),
            url: "./alterarSolicitacoesPerfil.do",
            success: function (dataR) {
               return dataR
            },
            error: function(errorMessage) {}
          });
};

暂无
暂无

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

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