在表单提交时使用jquery发送帖子数据 [英] sending post data with jquery on form submission
问题描述
如果我有这个表格将帖子数据提交给页面本身:
If I have this form which submits the post data to the page itself:
<form method="post">
<input type="text" name="name"/>
<input type="submit"/>
</form>
我如何能够使用JavaScript / jQuery注入额外的POST数据。如果我只使用任何函数通过ajax提交表单会更容易,例如 $ .post()
, $。get()
,或 $。ajax()
。但我想在这里做的是不通过ajax提交表单。
How will I be able to use JavaScript/jQuery to inject an additional POST data. This would be easier if I only submit the form via ajax using any of the functions like $.post()
, $.get()
, or $.ajax()
. But what I want to do here is to submit the form not via ajax.
附加数据是用JavaScript编写的。我正在考虑向DOM中注入一个新的隐藏字段,我将在其中传入数据,以便使用表单提交,但还有其他方法吗?
The additional data is in JavaScript. I'm thinking of just injecting a new hidden field into the DOM in which I will pass in the data so that it gets submitted with the form, but is there other way of doing it?
如果您需要更多代码/解释,请发表评论。
Please comment if you need more code/explanation.
推荐答案
使用常规按钮而不是使用提交按钮按钮并通过Javascript控制提交。在您的javascript中,您需要序列化表单并将其作为数据与您想要的任何其他内容一起传递。
Rather than using a submit button, use a regular button and control the submission via Javascript. In your javascript, you need to serialize the form and pass it as data along with anything else you want.
<script>
$(document).ready(function() {
var extra_data = "This is more stuff to send";
$('#submit').click(function() {
$.ajax({
type: "POST",
url: "form.php",
data: {'form': $("#my_form").serialize(), 'other': extra_data},
success: function(msg) {
alert("Form Submitted: " + msg);
}
});
});
});
</script>
<form id="my_form" method="post">
<input type="text" name="name" />
<input type="button" id="submit" />
</form>
这篇关于在表单提交时使用jquery发送帖子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!