转自:https://www.cnblogs.com/leejersey/p/3750259.html
使用serialize()提交form数据
jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,我们就可以选择一个或多个表单元素,也可以直接选择form将其序列化,如:
<form action=""> First name: <input type="text" name="FirstName" value="Bill" /><br /> Last name: <input type="text" name="LastName" value="Gates" /><br /> </form>
$(document).ready(function(){ console.log($("form").serialize()); // FirstName=Bill&LastName=Gates });
这样,我们就可以把序列化的值传给ajax()作为url的参数,轻松使用ajax()提交form表单了,而不需要一个一个获取表单中的值然后传给ajax(),举例如下:
$.ajax({ type: 'post', url: 'your url', data: $("form").serialize(), success: function(data) { // your code } });
使用$.post()、$.get()和$.getJSON()也是一样的:
$.post('your url', $("form").serialize(), function(data) { // your code } }); $.get('your url', $("form").serialize(), function(data) { // your code } }); $.getJSON('your url', $("form").serialize(), function(data) { // your code } });
使用serializeObject()将form表单中的数据序列化成对象
转自:https://blog.csdn.net/m0_37793545/article/details/79488277
在ajax中有 serializeArray()方法 可以将form表单中的数据序列化成如下的格式
[
{
name: "a",
value: "1"
},
{
name: "b",
value: "2"
},
{
name: "c",
value: "3"
},
{
name: "d",
value: "4"
},
{
name: "e",
value: "5"
}
]
但是有时候,我们需要将form表单序列化成对象的格式,那么封装一个简单的函数便会更简单
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
可以使用这个方法直接将from表单中的数据序列化成如下的对象格式
{
name:1,
age:11,
weight:60
}