我正在用 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 重新加载的情况下发送值,我正在为此使用以下代码:
$(".button").click(函数() { $('.error').隐藏();
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”。 有没有更优雅的方法来做到这一点。表格数量是动态的。
最佳答案
您可以很容易地获取单击按钮的父表单,但您可能还希望在表单上有一个唯一的 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;
});
关于php - 如何分离php生成的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13494551/