jQuery的serialize()方法经过序列化表单值,建立URL编码文本字符串,咱们就能够选择一个或多个表单元素,也能够直接选择form将其序列化,如:
html
<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
$.ajax({ type: 'post', url: 'your url', data: $("form").serialize(), success: function(data) { // your code } });
使用$.post()、$.get()和$.getJSON()也是同样的:post
$.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 } });