jQuery的serialize()方法通过序列化表单值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39709686/article/details/78718585

jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,我们就可以选择一个或多个表单元素,也可以直接选择form将其序列化,如:

<form id="dd" 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: $("#dd").serialize(),
    success: function(data) {
        // 其他代码
    }
});

使用$.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
    }
});

其他例子:
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<form class="form-horizontal" id="edit_customer_form">

.....
</form>

function updateCustomer() {
			$.post("<%=basePath%>customer/update.action",$("#edit_customer_form").serialize(),function(data){
				alert("客户信息更新成功!");
				window.location.reload();
			});
		}




猜你喜欢

转载自blog.csdn.net/weixin_39709686/article/details/78718585