Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

jquery - Send multiple Post requests using ajax on button click in the same page

Hi I am working on a jsp page, which renders multiple values dynamically and show a button on each value, when i click on each button i should trigger a ajax call which sends that value to the backend.

for example

value1 add

value2 add

when i click on add for value 1 then value 1 should be sending as part of the post request.

i cannot add id's for each element because as this page is a dynamic page. i have looked some of the stack overflow answers but they are all using ID in their element.

Please find the image if you have no idea what i am talking about Please suggest.

The jsp i wrote.

<%@ 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>


The controller class

@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";
    }

Please refer to the picture above to see how my products are getting displayed.

Note here that i cannot use ID since this is dynamic,i need to somehow get the data from the front end & send it to the controller class.

The above jquery doesn't work because the syntax is either false or wrong.

question from:https://stackoverflow.com/questions/65641877/send-multiple-post-requests-using-ajax-on-button-click-in-the-same-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Several issues:

  1. <div> is invalid child of <tbody> and invalid parent of <tr>.
  2. Use val() not text() to get value from form controls like <input>, <select> etc.
  3. You need the specific row instance of each of the values to send. To do that use closest() to isolate the row and find() to get the specific element within the row something like:

$(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
  });
});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...