Jquery easyui异步提交表单的两种方式

这篇文章分享一下easyui常用的两种表单异步提交的方式。

目录

开始前的准备工作

方式一:利用jquery ajax提交

$.post()

$.ajax()

方式二:使用easyui提供的表单提交方式


开始前的准备工作

1、使用HBuilderX创建一个简单的html项目,删除img和html目录,只保留js目录和index.html;

2、下载jquery.min.js和jquery.easyui.min.js,复制到js目录下;

3、修改index.html的代码,增加一个表单,包含三个输入框和一个提交按钮,在页面引入easyui的js文件;

页面效果如下:

方式一:利用jquery ajax提交

这种方式只需要引入jquery.min.js

$.post()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>easyui异步提交表单</title>
		<script src="js/jquery.min.js"></script>
	</head>
	
	<body>
		<form id="ajax_form">
			姓名:<input id="name" />
			年龄:<input id="age" />
			手机号:<input id="phone" />
			
			<button type="button" id="submit">提交</button>
		</form>
		
		<script>
			$(function(
				$("#submit").click(function() {
					$.post("/xxx/save", {
						name: $("#name").val(),
						age: $("#age").val(),
						phone: $("#phone").val()
					}, function(resp) {
						// 处理响应的数据
					}, "json");
				});
				
			));
		</script>
	</body>
</html>

$.ajax()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>easyui异步提交表单</title>
		<script src="js/jquery.min.js"></script>
	</head>
	
	<body>
		<form id="ajax_form">
			姓名:<input id="name" />
			年龄:<input id="age" />
			手机号:<input id="phone" />
			
			<button type="button" id="submit">提交</button>
		</form>
		
		<script>
			$(function(	
				$("#submit").on("click", function() {
					$.ajax({
						url: "/xxx/save",
						type: "post",
						data: {
							name: $("#name").val(),
							age: $("#age").val(),
							phone: $("#phone").val()
						},
						async: true,
						cache: false,
						dataType: "json",
						processData: true,
						success: function(resp) {
							// 处理成功的响应
						},
						error: function(resp) {
							// 处理失败的响应
						}
					});
				});
				
			));
		</script>
	</body>
</html>

方式二:使用easyui提供的表单提交方式

easyui官网已经介绍了这种方式,不过和上面的ajax提交不一样,这种提交方式要给输入框设置name属性。

案例代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>easyui异步提交表单</title>
		<script src="js/jquery.min.js"></script>
		<script src="js/jquery.easyui.min.js"></script>
	</head>
	
	<body>
		<form id="ajax_form" method="post">
			姓名:<input name="name" />
			年龄:<input name="age" />
			手机号:<input name="phone" />
			
			<button type="submit">提交</button>
		</form>
		
		<script>
			let requestUrl = "/xxx/save";
						
			$(document).ready(function() {
				$("#ajax_form").form({
					url: requestUrl,
					success: function(resp) {
						// 处理成功的响应
					}
				});
			
			});
		</script>
	</body>
</html>

好了,文章就分享到这里了,看完不要忘了点赞+收藏哦~

猜你喜欢

转载自blog.csdn.net/heyl163_/article/details/134860514