首页 > 解决方案 > 使用 ajax 和变量 id 提交刷新表单一个输入

问题描述

我需要 <span class="badge badge-light">在提交表单后刷新数字,而不需要在跨度中重新加载页面,而该表单的 id 为“ formid-<?php echo $i; ?>”,其中$i总是发生变化。我也需要 ajax 代码以及如何将它们组合在一起。我发现了类似的东西,但无法使其工作:

jQuery.on('submit', function(e){
e.preventDefault();
var formID = $(this).data('i');

//call $.ajax();

} 

和阿贾克斯:

$.ajax({
  type: 'POST',
  url: $("form").attr("action"),
  data: $("form").serialize(), 
  or your custom data either as object {foo: "bar", ...} or foo=bar&...
  success: function(response) { ... },
 });

我的表格是这样的:


<form action="" method="post" id="formid-<?php echo $i; ?>"> 
        <h6  class="badge badge-warning font top-8"><input type="submit" name="send" value="Subscribe">
   <span class="badge badge-light">

 <?php 

 echo $subscriptions; // this is the number

   ?>

   </span>
  <span class="sr-only">Subscribe</span>

</h6>
</form> 

标签: javascriptphpjqueryajax

解决方案


jQuery.on('submit'处理程序无效。即使您使用event-delegation,您也应该使用第二个参数作为选择器。

jQuery("form[id^='form-']").on('submit', function(e) {
    e.preventDefault();
    var formID = $(this).data('i');
    //call $.ajax();
  }
}

注意:使用事件委托,它将是jQuery("body").on("submit", "form[id^='form-']", function(){})


推荐阅读