2012-11-21 28 views
0

我生成按钮的表格用PHP如何单独的PHP生成按钮

echo ' <td"> 
<form action="test.php" method="POST"> 
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'"> 
<input type="hidden" id="service" name="service" value="'.$flavor.'"> 
<input type="hidden" id="running" name="running" value="false"> 
<input type="submit" value="OFF" class="button"> 
</form> 
</td>'; 

我要发送的值,而无需通过jQuery AJAX重装,我用这个代码是:

$( “按钮”)点击(函数(){ $( '错误')隐藏();

var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value; 

    $.ajax({ 
     type: "POST", 
     url: "test.php", 
     data: dataString, 
     success: function() { 
      alert ("Success"); 
     } 
    }); 
    return false; 
}); 

代码工作至今 - 它只是总是从第一种形式发送数据。区分两者的最佳方式是什么?所有的按钮。我可以在表格中使用一个计数器,但是我会如何精确地写出js“ifs”。 有没有更好的方法来做到这一点。表格数量是动态的。

回答

0

最好的方法是对表单元素使用唯一的ID。另一种方法是将类设置为具有相同名称的多个元素。

但是,下面的方法更可取:

$("form").on("submit", function() { 
    $.ajax({ 
     type: "POST", 
     url: "test.php", 
     data: $(this).serialize(), 
     success: function() { 
      alert ("Success"); 
     } 
    }); 
    return false; 
}); 

(但无论如何不要忘记删除从表单元素复制id属性。)

1

你可以抓住的父窗体按钮很容易点击,但你也可能想在表单上为其他事物设置一个唯一的ID。此外,您还需要删除输入上的ID或使其唯一。

echo ' <td"> 
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '> 
<input type="hidden" name="node" value="'.$fnode->{'name'}.'"> 
<input type="hidden" name="service" value="'.$flavor.'"> 
<input type="hidden" name="running" value="false"> 
<input type="submit" value="OFF" class="button"> 
</form> 
</td>'; 


$(".button").click(function(e) { 
    e.preventDefault(); 
    $('.error').hide(); 
    var $form = $(this).closest('form'), // the closest parent form 
     dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding 
    $.ajax({ 
     type: "POST", 
     url: "test.php", 
     data: dataString, 
     success: function() { 
      alert ("Success submitting form ID " + $form.attr('id')); 
      // you can now modify the form you submitted 
     } 
    }); 
    return false; 
}); 
+0

这是正确的答案。 – OneOfOne

0

你可以给每一个提交按钮的ID:

<input id="button-1" type="submit" value="OFF" class="button"> 

,然后触发上的特定按钮的点击事件:

$("#button-1").click(function() { ... });