简体   繁体   中英

How to construct ajax payload dynamically with multiple values

So with my code below - each checkbox that is checked results in a ajax request being sent. However what I want is a single ajax request with all the names of the checkboxes being sent in the payload. How exactly can I do this? In Python I would just create a list or dictionary and send that - but not sure how to do this with js.

function save_product(data) {
    $('input[class="product"]:checked').each(function() {
        $.ajax({
            type:"GET",
            url:"/edit_view/",
            data: {
                product_name:name,
            },
            success: function(data){}
        });
    })
}

what I want is a single ajax request with all the names of the checkboxes being sent in the payload

In Python I would just create a list or dictionary and send that - but not sure how to do this with js

Well intuitively just like in Python actually


function save_product(data) {
  var products = []
  $('input[class="product"]:checked').each(function(chk) {
    var product = chk.val()
    products.push(product)
  });

  $.ajax({
    type:"GET",
    url:"/edit_view/",
    data: {
      product_name: products,
    },
    success: function(data){
      // Handle response
    }
  });
}

You can take advantage of various js sugar, and jquery sugar. .map is a great tool to start thinking in functional programming. Like so :

var products = $('input[class="product"]:checked').map(function(chk) {
  return chk.val()
})
// products === [1, 7, 12]
// assuming you put the product.id inside checkbox value= attribute

@Karan Patel answer above uses a lambda expression, which is ES6 and might not be well suited for you if you do not transpile your code before running it in the browser. But sure you can simplify it with chk => chk.val() being equivalent of function(chk) { return chk.val() } , like so :

var products = $('input[class="product"]:checked').map(chk => chk.val())

Bonus :

1)

If you're starting javascript, you should from now start leaving the "callback pattern" for every async operations, and start using at least "Promise pattern". Read this .

Like so :

$.ajax({
  type:"GET",
  url:"/edit_view/",
  data: {
    product_name: products,
  }
})
.then(function(data) {
  // Handle response
})
.catch(function(err) {
  // Handle error
});

2)

You're targetting and grouping product values with input[class="product"] which you can simplify input.product . Be very careful with attribute selector , as in your syntax, <input class="product custom-product"> won't match your selector (your targetting exactly product word in class. But in your precise case, you might want to target more semantically and accurately your input's with something like form.my-form input[name=product_name] to target

<form class="my-form">
  <input type="checkbox" name="product_name" value="1" />
  <input type="checkbox" name="product_name" value="2" />
</form>

(name attribute is precisely designed to identify inputs, uniquely)

3) And finally, just because you have to hear it, jQuery is not required for such a simple operation nowadays

Here I'm using plain js to get values, and axios to ajax the stuff.

var productsChks = document.querySelectorAll('input.product')
var products = products.map(productChk => productChk.value)

axios.get('/edit_view/', {data: products})
.then(function(data) {
  // Handle data
})

Be careful of browser support

Note you can also use a native browser API for ajax, fetch , stil being careful of browser support and the potential need of a polyfill

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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