表单内部while循环只通过ajax发送第一行数据

时间:2018-03-04 08:37:27

标签: javascript php html ajax

我在while循环中有一个表单,我想用它来使用ajax更新数据库。问题是当我使用ID时,无论我点击哪个按钮,都会发送表格的第一个数据或第一行数据。当我将ID更改为CLASSES时,控制台显示未定义。

使用类时控制台出错:

  

Object {credits:undefined,price:undefined,packId:undefined,type:" savePackage" }

HTML表单:

<div class="content">
        <div class="content table-responsive table-full-width">
          <table class="table table-hover table-striped">
            <tr>
              <th>Credits</th>
              <th>Price</th>
              <th>Action</th>
            </tr>
            <?php while($pack = $package->fetch()){ extract($pack); ?>
              <tr>
                <form method="post" action="">
                  <input type="hidden" value="<?php echo $cp_id; ?>" class="packId">
                  <td><input type="text" class="form-control" class="editCredits" value="<?php echo $cp_credits; ?>"></td>
                  <td><input type="text" class="form-control" class="editPrice" value="<?php echo $cp_price; ?>"></td>
                  <td>
                    <input type="submit" value="Save" class="btn btn-fill btn-info savePackage">
                    <input type="submit" value="Delete" class="btn btn-fill btn-danger deletePackage">
                  </td>
                </form>
              </tr>
            <?php } ?>
          </table>
        </div>
      </div>

AJAX代码

$(document).ready(function() {
  $(".savePackage").click(function() {
    var dataString = {
      credits: $(this).closest('form').find('.editCredits').val(),
      price: $(this).closest('form').find('.editPrice').val(),
      packId: $(this).closest('form').find('.packId').val(),
      type: 'savePackage'
    };
    console.log(dataString);
    var $submit = $(this).parent().find('.savePackage');
    $.confirm({
      title: 'Confirm!',
      content: 'Are you sure you want to add this package?',
      buttons: {
        confirm: function () {
          $.ajax({
            type: "POST",
            //dataType : "json",
            url: "ptc-settings-process.php",
            data: dataString,
            cache: true,
            beforeSend: function(){
              $submit.val("Please wait...");
            },
            success: function(html){
              $.alert(html);
              $submit.val("Save");
            }
          });
        },
        cancel: function(){}
      }
    });
    return false;
  });
});

我在这里使用了$(this).closest('form').find('.editCredits').val()方法,但同一页面上还有其他多种形式。因此,使用$(this).closest('form')中的表单元素可能会导致问题。

0 个答案:

没有答案