在同一页面中点击按钮时使用 ajax 发送多个 Post 请求

时间:2021-01-09 11:03:41

标签: jquery ajax

嗨,我正在处理一个 jsp 页面,它动态呈现多个值并在每个值上显示一个按钮,当我点击每个按钮时,我应该触发一个 ajax 调用,该调用将该值发送到后端。

例如

value1 添加

value2 添加

当我点击添加值 1 时,值 1 应该作为发布请求的一部分发送。

我不能为每个元素添加 id,因为这个页面是一个动态页面。 我查看了一些堆栈溢出的答案,但它们都在其元素中使用 ID。

Please find the image 如果您不知道我在说什么,请提出建议。

我写的jsp。

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<title>Items List</title>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<h1>Welcome to LassiShop </h1>
<c:set var="url" value="/cart"/>
<c:if test="${itemsData.size() gt 0}">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Price</th>
        <th scope="col">Quantity</th>
      </tr>
    </thead>
    <tbody>
      <c:forEach items="${itemsData}" var="item">
      <div class="form">
        <tr>
          <td>
            <c:out value="${item.name}"/>
            <input type="hidden" class="name" value="${item.name}">
          </td>
          <td>
            <c:out value="${item.price}"/>
            <input type="hidden" class="price" value="${item.price}">
           </td>
          <td><input type="number" class="quantity"/></td>
          <td><button class="btn btn-primary" type="submit">ADD TO CART</button></td>
        </tr>
       </div>
      </c:forEach>
    </tbody>
  </table>
</c:if>
<c:if test="${itemsData.size() eq 0}">
    <h3>No Products available for this Category</h3>
</c:if>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script>
$(document).on('click',".btn",function(){
var itemData = {};
    itemData["name"] = $('.name').text();
    itemData["price"] = $('.price').text();
    itemData["quantity"] = $('.quantity').text();
    console.log(itemData);
    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : "/cart",
        data : JSON.stringify(itemData),
        dataType : 'json',
        async:true
    });
});
</script>
</body>
</html>


控制器类

@RequestMapping(value = "/cart", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody String testCart(@RequestBody CartEntryData cartEntry){
        System.out.println(cartEntry.getName());
        System.out.println(cartEntry.getPrice());
        System.out.println(cartEntry.getQuantity());
        return "itemsList";
    }

请参考上图了解我的产品是如何展示的。

请注意,我不能使用 ID,因为这是动态的,我需要以某种方式从前端获取数据并将其发送到控制器类。

上面的 jquery 不起作用,因为语法错误或错误。

1 个答案:

答案 0 :(得分:0)

几个问题:

  1. <div><tbody> 的无效子代和 <tr> 的无效父代。
  2. 使用 val() 而不是 text()<input><select> 等表单控件中获取值。
  3. 您需要每个要发送的值的特定行实例。为此,请使用 closest() 来隔离行并使用 find() 来获取行中的特定元素,例如:

$(document).on('click', ".btn", function() {
  // `this` is the button event occured on
  var $row = $(this).closest('tr');
  
  var itemData = {
    name: $row.find('.name').val(),
    price: $row.find('.price').val(),
    quantity: $row.find('.quantity').val()

  };
  console.log(itemData)
  $.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/cart",
    data: JSON.stringify(itemData),
    dataType: 'json',
    //async: true  pointless as this is default
  });
});

相关问题