簡體   English   中英

如何在javascript中獲取foreach輸入值並將其傳遞給ajax數據?

[英]How to get foreach input value in javascript and pass it to ajax data?

這是我的表格

<form method="post" id="BargainForm">
    <input type="hidden" name="pro_id" class="pro_id" id="pro_id" value="<?php echo $pro_id; ?>">
    <input type="hidden" name="customer_id" class="customer_id" id="customer_id" value="<?php echo $customer_id; ?>">
    <input type="text" name="bargain_qty" class="bargain_qty" id="bargain_qty" placeholder="Qty" required/></br></br>
    <?php if($productType = 'Configurable'): ?>
        <?php foreach($attributes as $attribute): ?>
            <input type="text" name="<?php echo strtolower($attribute['store_label']); ?>" 
                                        class="<?php echo strtolower($attribute['store_label']); ?>" 
                                        id="<?php echo strtolower($attribute['store_label']); ?>" 
                                        placeholder="<?php echo $attribute['store_label'] ?>"></br></br>
        <?php endforeach; ?>
    <?php else: ?>

    <?php endif; ?>
    <input type="text" name="bargain_price" class="bargain_price" id="bargain_price" placeholder="Total Price" required/></br></br>
    <input type="submit" name="bargain_btn" class="bargain_btn">
</form>

這是我的JavaScript代碼

<script type="text/javascript">
$(function () {
    $('.bargain_btn').click(function(e) {
        var qty = $( "#bargain_qty" ).val();
        var price = $( "#bargain_price" ).val();
        var pro_id = $( "#pro_id" ).val();
        var customer_id = $( "#customer_id" ).val();
        var att_lable = $( "#<?php echo strtolower($attribute['store_label']); ?>" ).val();
        alert(att_lable);
        e.preventDefault();
        $.ajax({
            url: "<?php echo Mage::getUrl('bargain/Ajax/index'); ?>",
            type: "POST",
            data: {qty,price,pro_id,customer_id},
            success: function(data) {
                if(data.success) {
                }
            }
        });
    });
});

在形式上,我正在使用foreach。 如果我有2個數據,那么它將顯示2個輸入標簽,我只是不知道如何保存該2個輸入的值並將其傳遞給data: {qty,price,pro_id,customer_id},

先感謝您!

為使用循環生成的所有文本框提供通用類:

foreach(...)
{
   echo '<input class="myTxt" value="" id="" />';
}

jQuery的:

var arr = [];
$('.myTxt').each(function(){
    arr.push($(this).val());
});

通過序列化或在索引上將data {}部分的該數組(即arr)傳遞給ajax調用。

不使用:

data: { qty, price, pro_id, customer_id },

而是使用:

data: $("#BargainForm").serialize(),

僅當您的$attribute['store_label']名稱是唯一$attribute['store_label']

更換

data: {qty,price,pro_id,customer_id},

通過

data: "qty="+qty+"&price="+price+"&pro_id="+pro_id+"&customer_id="+customer_id+"&att_lable="+att_lable,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM