jQuery提交了错误的html表单


jQuery submits the wrong html form

我有一个php脚本,它从数据库中提取项目,并允许用户投票给它们,我给每个提取的项目一个(html表单),其中有一个(输入文本字段)和一个(提交按钮),以便在点击时提交输入的分数,我在同一页面中有一个jQuery脚本,它通过该表单将分数插入数据库,而无需刷新页面,除了剧本有一个外,一切似乎都很顺利。

这个脚本只允许循环中的第一个(html表单)提交,而第一个(html表单)会影响循环中不跟随它的项,如何使每个表单都归属于它的项?

除此之外,我还希望脚本为提交分数的用户返回一个通知,通知他们数据是成功插入还是失败,当成功时,我希望用户提交的分数在提交后为他们显示

感谢您的帮助,这是我的代码:

<body>
  <div id="items-wrapper">
    <?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
    <div id="item">
      <?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
      <ul id="responds">
        <!--i want to append data here-->
      </ul>
      <img src="<?php echo $item_file; ?>" />
      <form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
        <input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
        <button id="FormSubmit">Add Score</button>
        <img src="images/loading.gif" id="LoadingImage" style="display:none" />
      </form>
      <?php } ?>
    </div>
    <?php } ?>
  </div>
  <script type="text/javascript">
    $(document).ready(function() {
      //Ajax request to setItemScore.php
      $("#FormSubmit").click(function(e) {
        e.preventDefault();
        if ($("#contentText").val() === '') {
          alert("Please enter some text!");
          return false;
        }
        $("#FormSubmit").hide();
        $("#LoadingImage").show();
        var myData = 'score_value=' + $("#contentText").val();
        jQuery.ajax({
          type: "POST",
          url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
          dataType: "text",
          data: myData,
          success: function(response) {
            $("#responds").append(response);
            $("#contentText").val('');
            $("#FormSubmit").show();
            $("#LoadingImage").hide();
          },
          error: function(xhr, ajaxOptions, thrownError) {
            $("#FormSubmit").show();
            $("#LoadingImage").hide();
            alert(thrownError);
          }
        });
      });
    });
  </script>
</body>

问题#1

在提交表单时,您应该始终使用.submit()方法,而不是使用提交按钮onclick(),原因有两个。1) 当使用inputs时,您可以点击回车键并绕过整个方法提交表单。2) .submit()使用允许您获取该表单的子项的表单。

考虑到这一点,我会为您知道的通过ajax提交的表单添加一个类名,比如:

<form class="ajax-form" action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
...
</form>

然后,您可以使用:而不是使用.onclick()

$('.ajax-form').submit(function(e){
...
});

问题#2

在AJAX请求中,您使用以下行:

url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",

这总是将$_itemid设置为上面foreach()循环的最后一次迭代,而不是表单中的action

如果你使用上面在问题#1中提到的方法,那么你可以简单地使用forms-action属性:

url: $(this).prop('action')

$(this)是形式.