Featured image of post JQuery - Form 序列化物件 serialize

JQuery - Form 序列化物件 serialize

serialize serializeArray 使用

JQuery Form 序列化物件

<form id="form">
    <input name="FirstName" value="Bill" type="text">
    <input name="LastName" value="Gates" type="text">
</form>
$(form).serialize()
// 會轉換成 => FirstName=Bill&LastName=Gates
$(form).serializeArray()
// 會轉換成 => [{name:"FirstName",value:"Bill"},{name:"LastName",value:"Gates"}]

製作成 util function: serializeObject()

function serializeObject(el) {
	var formData = {};
	var formArray = el.serializeArray();
	for (var i = 0, n = formArray.length; i < n; ++i) {
		formData[formArray[i].name] = formArray[i].value;
	}
	return formData;
};
// 使用方式 => serializeObject($(form))
// 會轉換成 => { "FirstName" : "Bill", "LastName" : "Gates" }
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus