我在 Jquery 中遇到问题。这是我在 php 文件中的部分代码。
echo '<form action="add.php" method="post" id="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="img_link" value="'.$data["img_link"].'">';
echo '<input style="display:none" type="text" name="pro_url" value="'.$data["pro_url"].'">';
echo '<input style="display:none" type="text" name="pro_price" value="'.$data["pro_price"].'">';
echo '<input style="display:none" type="text" name="total_fb" value="'.$data["total_fb"].'">';
echo '<input style="display:none" type="text" name="pro_id" value="'.$data["pro_id"].'">';
echo '<input style="display:none" type="text" name="pro_name" value="'.$data["pro_name"].'">';
echo '</form>';
我需要提交表单但停留在同一页面上,所以我使用了下面的代码。它确实适用于不转到其他页面,但我如何获得此表单的 ID?当我输出 id 但结果将是 NoneType。
$('form').live('submit', function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
var id = $(this).attr('id');
document.write(id);
}, 'json');
return false;
});
最佳答案
您使用的是正确的方法,但您的问题是 $.post()
调用中的 this
未引用触发提交事件的元素.因此,您需要将该行移至外部范围。
这里还有几件事需要解决。首先请注意 live()
很久 以前就被弃用了。您应该检查您正在使用的 jQuery 版本,因为它至少应该是 1.12.1,或者更好的是 3.3.1(在撰写本文时),并且您应该使用 on()
反而。
其次你不应该使用document.write()
。相反,您可以使用 jQuery 选择要更新的元素,然后对其调用 html()
。试试这个:
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var id = this.id;
$.post(this.action, $(this).serialize(), function(response) {
$('#targetElement').html(id);
}, 'json');
});
关于jQuery 从元素中获取 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289598/