使用 AJAX 和 jQuery 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/425095/
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
Submit form using AJAX and jQuery
提问by Chris Bartow
It seems like this should be something built into jQuery without the need for more than a few lines of code, but I can't find the "simple" solution. Say, I have an HTML form:
看起来这应该是 jQuery 内置的东西,不需要多行代码,但我找不到“简单”的解决方案。说,我有一个 HTML 表单:
<form method="get" action="page.html">
<input type="hidden" name="field1" value="value1" />
<input type="hidden" name="field2" value="value2" />
<select name="status">
<option value=""></option>
<option value="good">Good</option>
<option value="bad">Bad</option>
</select>
</form>
When someone changes the select field, I would like to submit the form using ajax to update the database. I thought there would be some way to do the following without manually creating the values/attributes, just send them all, like:
当有人更改选择字段时,我想使用 ajax 提交表单以更新数据库。我认为有一些方法可以在不手动创建值/属性的情况下执行以下操作,只需将它们全部发送,例如:
$("select").change(function(){
$.get("page.html?" + serializeForm());
});
What am I missing?
我错过了什么?
采纳答案by Chris Bartow
This is what ended up working.
这就是最终的工作。
$("select").change(function(){
$.get("/page.html?" + $(this).parent("form").find(":input").serialize());
});
回答by rfunduk
First give your form an id
attribute, then use code like this:
首先给你的表单一个id
属性,然后使用这样的代码:
$(document).ready( function() {
var form = $('#my_awesome_form');
form.find('select:first').change( function() {
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );
} );
So this code uses .serialize()
to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.
所以这段代码用于.serialize()
从表单中提取相关数据。它还假定您关心的选择是表单中的第一个。
For future reference, the jQuery docsare very, very good.
为了将来参考,jQuery文档非常非常好。
回答by Darin Dimitrov
There is a nice form pluginthat allows you to send an HTML form asynchroniously.
有一个不错的表单插件,它允许您异步发送 HTML 表单。
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
或者
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
立即提交表格