Javascript AJAX添加到购物车、自定义变体选择器、将按钮productID设置为所选变体

Javascript AJAX添加到购物车、自定义变体选择器、将按钮productID设置为所选变体,javascript,php,jquery,wordpress,woocommerce,Javascript,Php,Jquery,Wordpress,Woocommerce,我试图创建一个变体选择器和一个按钮,将所选变体添加到购物车中 所以,若产品是“variable”类型,我创建一个选择器,然后用产品的变体填充该选择器 <?php if ($product->is_type( 'variable' )) { $available_variations = $product->get_available_variations(); ?> <select class="field&q

我试图创建一个变体选择器和一个按钮,将所选变体添加到购物车中

所以,若产品是“variable”类型,我创建一个选择器,然后用产品的变体填充该选择器

<?php
    if ($product->is_type( 'variable' )) 
    { 
        $available_variations = $product->get_available_variations();
 ?>     <select class="field">
        <option value="">Choose an option</option>
                        
  <?php foreach ($available_variations as $key => $value) 
        { ?>
            <option value="<?php echo $value['variation_id']; ?> "><?php echo $value['attributes']['attribute_flavor']; echo $value['attributes']['attribute_size'];  echo $value['attributes']['attribute_strength']; echo $value['attributes']['attribute_type']; echo $value['attributes']['attribute_formulation'];?> </option>
  <?php } ?>
        </select>  
  <?php } ?>
                
     <button type="submit" data-quantity="1" class="button product_type_simple add_to_cart_button ajax_add_to_cart single_add_to_cart_button" data-product_id="<?php echo $product->id; ?>" rel="nofollow">Add To Cart</button> 

选择一个选项
<script>
$(document).ready(function(){
    var selectedProduct = "none";


    $('.field').change(function(e) {
        var target = e.target;
        selectedProduct = this.value;
        //alert(this.value);

        //$(e.target).closest('form').find("button")
        //attr('href', selectedProduct)
    });

});
</script>
<script>
$(document).ready(function(){


function setAjaxButtons() {
   $('.single_add_to_cart_button').click(function(e) {
      var target = e.target;
      //loading(); // loading
      e.preventDefault();
      var dataset = $(e.target).closest('form');
      var product_id = $(e.target).closest('form').find("select[value*='product_id']");
      values = dataset.serialize();

        $.ajax({
          type: 'POST',
          url: '?add-to-cart='+product_id.val(),
          data: values,
          success: function(response, textStatus, jqXHR){
                loadPopup(target); // function show popup
                updateCartCounter();
            },
        });    
      return false;
   });    

}
});
</script>