如何在javascript中获取foreach输入值并将其传递给ajax数据?

时间:2016-12-12 07:13:56

标签: javascript php jquery ajax

这是我的表格

<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},

提前谢谢!

3 个答案:

答案 0 :(得分:2)

为使用循环生成的所有文本框提供公共类:

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

Jquery的:

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

使用序列化或索引将此数组(即 arr )传递给data {}部分中的ajax调用。

答案 1 :(得分:1)

不要使用:

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

改为使用:

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

仅当您的$attribute['store_label']名称是唯一的时才会有效。

答案 2 :(得分:1)

替换

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

通过

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