在 jQuery Ajax 函数中将整个表单作为数据传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2019608/
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
Pass entire form as data in jQuery Ajax function
提问by Brian
I have a jQuery ajax function and would like to submit an entire form as post data. We are constantly updating the form so it becomes tedious to constantly update the form inputs that should be sent in the request.
我有一个 jQuery ajax 函数,想提交整个表单作为发布数据。我们不断更新表单,因此不断更新应在请求中发送的表单输入变得乏味。
回答by Will Vousden
There's a function that does exactly this:
有一个函数可以做到这一点:
http://api.jquery.com/serialize/
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
回答by Moh Arjmandi
serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.
如果您想使用 post 方法发送表单, serialize() 不是一个好主意。例如,如果您想通过 ajax 传递文件,则它不起作用。
Suppose that we have a form with this id : "myform".
假设我们有一个带有这个 id 的表单:“myform”。
the better solution is to make a FormData and send it:
更好的解决方案是制作一个 FormData 并发送它:
var myform = document.getElementById("myform");
var fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
}
});
回答by nikola
In general use serialize()
on the form element.
通常用于serialize()
表单元素。
Please be mindful that multiple <select> options are serialized under the same key, e.g.
请注意多个 <select> 选项在同一个键下被序列化,例如
<select id="foo" name="foo" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
will result in a query string that includes multiple occurences of the same query parameter:
将产生一个查询字符串,其中包含多次出现的相同查询参数:
[path]?foo=1&foo=2&foo=3&someotherparams...
which may not be what you want in the backend.
这可能不是您想要的后端。
I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):
我使用此 JS 代码将多个参数减少为逗号分隔的单个键(从 John Resig 处的线程中的评论者的回复中无耻地复制):
function compress(data) {
data = data.replace(/([^&=]+=)([^&]*)(.*?)&([^&]*)/g, ",");
return /([^&=]+=).*?&/.test(data) ? compress(data) : data;
}
which turns the above into:
将上述内容变成:
[path]?foo=1,2,3&someotherparams...
In your JS code you'd call it like this:
在您的 JS 代码中,您可以这样称呼它:
var inputs = compress($("#your-form").serialize());
Hope that helps.
希望有帮助。
回答by rahul
Use
用
var str = $("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
将表单序列化为查询字符串,该字符串可以在 Ajax 请求中发送到服务器。
回答by patrick
A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!
执行此操作的一个很好的 jQuery 选项是通过FormData。这种方法也适用于通过表单发送文件!
<form id='test' method='post' enctype='multipart/form-data'>
<input type='text' name='testinput' id='testinput'>
<button type='submit'>submit</button>
</form>
Your send function in jQuery would look like this:
您在 jQuery 中的发送函数如下所示:
$( 'form#test' ).submit( function(){
var data = new FormData( $( 'form#test' )[ 0 ] );
$.ajax( {
processData: false,
contentType: false,
data: data,
dataType: 'json',
type: $( this ).attr( 'method' );
url: 'yourapi.php',
success: function( feedback ){
console.log( "the feedback from your API: " + feedback );
}
});
to add data to your form you can either use a hidden input in your form, or you add it on the fly:
要将数据添加到表单中,您可以在表单中使用隐藏输入,也可以即时添加:
var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );
回答by DANISH TAYYIB
You just have to post the data. and Using jquery ajax function set parameters. Here is an example.
你只需要发布数据。和使用 jquery ajax 函数设置参数。这是一个例子。
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'your_complete url',
data: $('form').serialize(),
success: function (response) {
//$('form')[0].reset();
// $("#feedback").text(response);
if(response=="True") {
$('form')[0].reset();
$("#feedback").text("Your information has been stored.");
}
else
$("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
}
});
});
});
</script>
回答by rubo77
The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.
其他解决方案对我不起作用。也许我正在处理的项目中的旧 DOCTYPE 阻止了 HTML5 选项。
My solution:
我的解决方案:
<form id="form_1" action="result.php" method="post"
onsubmit="sendForm(this.id);return false">
<input type="hidden" name="something" value="1">
</form>
js:
js:
function sendForm(form_id){
var form = $('#'+form_id);
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(result) {
console.log(result)
}
});
}