2017-10-19 19 views
0

对于表中的每一行,提交按钮的以下表单正在被回显。使用相同的ajax的多个提交

echo '<form method="POST" name="implement" id="implement" action="submit.php?data='.$data.'" style="display: inline;"> 
<input type="submit" name="submit" value="Implement"> 
</form>'; 

每个提交按钮必须能够使用下面的javascript。我无法弄清楚如何为每个表单分配一个唯一的ID。

<script> 
$(function(){ 
    $('#implement).on('submit', function(e){ 

     // prevent native form submission here 
     e.preventDefault(); 


     // now do whatever you want here 
     $.ajax({ 
      type: $(this).attr('method'), // <-- get method of form 
      url: $(this).attr('action'), // <-- get action of form 
      data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file 
      beforeSend: function(){ 
       $('#result').html(''); 
      }, 
      success: function(data){ 
       $('#result').html(data); 


     if(data === "0") { 
alert("label1"); 
     } 

    if(data === "1") { 
alert("label2"); 
     } 



      } 
     }); 
    }); 
}); 
</script> 
+0

你可以通过班级而不是Id或者'form'来完成。 – Rasclatt

回答

0

正如指出的那样,你可以只使用一个类或form标签本身作为听众,我将使用类:

// Presumably this is in your loop 
// I was start by removing the id since it's not unique 
// I would also put whatever data you are trying to submit in the $_GET into a hidden field 
?> 
<form method="POST" name="implement" class="form-submit" action="submit.php" style="display: inline;"> 
<input type="hidden" name="data" value="<?php echo $data ?>" /> 
<input type="submit" name="submit" value="Implement"> 
</form> 
<?php 

AJAX的JavaScript:

<script> 
$(function(){ 
    // Target the class name, now it will apply to all forms with this class 
    $('.form-submit').on('submit', function(e){ 
     // prevent native form submission here 
     e.preventDefault(); 
     $.ajax({ 
      type: $(this).attr('method'), 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $('#result').html(''); 
      }, 
      success: function(data){ 
       $('#result').html(data); 
       if(data === "0") { 
        alert("label1"); 
       } 
       else if(data === "1") { 
        alert("label2"); 
       } 
      } 
     }); 
    }); 
}); 
</script> 
相关问题