首页 > 解决方案 > Ajax 调用表单的第二个提交按钮

问题描述

我正在使用弹簧靴和百里香。管理在单击第一个提交按钮时调用弹簧控制器方法。我正在尝试在点击第二个提交按钮时进行 Ajax 调用,我该如何实现?

Ajax 调用第二个提交按钮

$(document).ready(function() {
  $("#download").click(function() {
    var checked = [];
    $('.checkbox:checked').each(function() {
      checked.push($(this).val());
    });

    console.log(checked);
    $.ajax({
      type: "POST",
      url: "selectedsalesDownload",
      data: {
        name: checked
      },
      success: function(msg) {
        console.log(mgs);
        alert(msg);
      }
    });
  });
});
<form name="salesList" th:action="@{/selectedsales}" th:object="${sales}" method="post">
  <div class="container">
    <hr>
    <table class="table table-striped">
      <thead class="thead-dark">
        <tr>
          <th>SELECT</th>
          <th>Mandy Name</th>
          <th>GSTIN</th>
        </tr>
      </thead>
      <tbody>
        <tr id="salesDataTable" th:each="tempSales:${sales}">
          <td>
            <input class="checkbox" type="checkbox" th:name="selected" th:value="${tempSales.ID}" />
          </td>
          <td th:text="${tempSales.mandyName}"></td>
          <td th:text="${tempSales.gstin}"></td>
        </tr>
      </tbody>
    </table>
    <div>
      <input type="submit" value="SELECT" name="submit" class="btn btn-primary btn-sm mb-3" />
      <input id="download" type="submit" value="DOWNLOAD" name="download" class="btn btn-primary btn-sm mb-3" />
    </div>
  </div>
</form>

第一次提交按钮的控制器方法

@PostMapping("/selectedsales")
public String selectedSales(
        @RequestParam(value = "selected", required = false) List<Integer> selectedList,
        Model model
) {
    //...
}

第二个提交按钮的控制器方法

@RequestMapping(value = "/selectedsalesDownload")
@ResponseBody
public String toDownload(@RequestParam("name") List<Integer> list) {
    return "msg";
}

单击第二个提交按钮时,我无法进入控制器中的“toDownload”方法,而是进入第一个提交按钮控制器方法“selectedSales”。

而且我还需要将存储在javascript数组变量“checked”中的复选框值发送到spring控制器方法“toDownload”。

需要解决方案。

标签: javascriptjqueryajaxspring-bootform-submit

解决方案


这里有两件事...

  1. 您不会阻止第二个提交按钮正常提交表单。要么使用按钮类型...

    <input id="download" type="button" ... />
    

    或确保阻止默认事件操作

    $("#download").on("click", function(e) {
      e.preventDefault()
      // and so on
    })
    
  2. @RequestParam列表参数应使用以下格式发送以获得最大的兼容性

    name=1&name=2&name=3...
    

    不幸的是,jQuery 的默认值是

    name[]=1&name[]=2&name[]=3...
    

    可能是为了与 PHP 兼容。您可以通过traditional选项更改此设置

    $.ajax({
      method: "POST",
      url: "selectedsalesDownload",
      data: {
        name: checked
      },
      traditional: true, //  note the value here
      success: function(msg) {
        console.log(mgs);
        alert(msg);
      }
    });
    

    请参阅https://api.jquery.com/jquery.ajax/更具体地说https://api.jquery.com/jQuery.param/


推荐阅读