Javascript 在表单提交时使用 jquery 发送帖子数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10863074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sending post data with jquery on form submission
提问by Wern Ancheta
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>
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/jQuery 注入额外的 POST 数据。如果我只使用任何的功能,如通过AJAX提交表单这会更容易些$.post()
,$.get()
或$.ajax()
。但我想在这里做的是不通过ajax提交表单。
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?
附加数据在 JavaScript 中。我正在考虑将一个新的隐藏字段注入到 DOM 中,我将在其中传递数据,以便它与表单一起提交,但是还有其他方法吗?
Please comment if you need more code/explanation.
如果您需要更多代码/解释,请发表评论。
回答by Jeremy Harris
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.
不要使用提交按钮,而是使用常规按钮并通过 Javascript 控制提交。在您的 javascript 中,您需要序列化表单并将其作为数据与您想要的任何其他内容一起传递。
<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>
回答by Raja Manickam
<head>
<script src="jquery/jquery-1.11.1.min.js"></script>
<script>
$(function () {
$('#form_id').on('click','#submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "get_Ajax.php",
data: $('#form_id').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
</head>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="button" id="submit" name="submit" value="Send">
</form>
** get_ajax.php**
** get_ajax.php**
<?php
$ime = $_POST['ime'];
echo "Your name is $ime";
?>