多个提交使用相同的ajax

时间:2017-10-19 17:27:09

标签: javascript php jquery

对于表格中的每一行,都会回显以下带有“提交”按钮的表单。

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> 

1 个答案:

答案 0 :(得分: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>