利用ajax提交表单,实现数据前端后台数据交互的完整流程演示

该演示需要用到  1 : json.jar(下载)

                              2 : jquery.js(下载)

流程演示:1.点击“登录”按钮,传参到后台

                    2.后台获取数据,处理分析数据,利用JSONObject返回结果(JSONObject需要用到一个 json.jar 即可)

                   3.前端获取后台返回的结果进行判断,然后前端分析该结果,再决定进入后台的最后一个环节(登录是否成功的跳转)

                   4.页面跳转


效果演示:

登录页面:



用户名密码都正确,跳转到index



工程目录树:




具体流程:

1,在WebContent目录下新建一个toLogin.jsp , 用于跳转到login.jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="login.do?method=0"></jsp:forward>

2.Servlet:

@WebServlet("/login.do")  //servlet的名字
public class login extends HttpServlet {

	
	private static final long serialVersionUID = 4306651429943204510L;
	
	public final static String To_login_Page = "0";
	public final static String login = "1";
	public final static String index = "2";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String method =  req.getParameter("method");
		switch(method){
		case To_login_Page:
			To_login_Page(req,resp);
			break;
		case login:
			login(req,resp);
			break;
		case index:
			index(req,resp);
			break;
		}
	}

	private void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("WEB-INF/view/index.jsp").forward(req, resp);
		
	}
	
	private void To_login_Page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("WEB-INF/view/login.jsp").forward(req, resp);
	}
	
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		System.out.println(username);
		System.out.println(password);
		boolean IsOK = false;
		if(username.equals("admin")&&password.equals("123456")){
			IsOK = true;
		}else{
			IsOK = false;
		}
		try {
			JSONObject json = new JSONObject();
			json.put("IsOK", IsOK);
			PrintWriter out = resp.getWriter();
			out.println(json.toString());
			out.close();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

3.login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>login</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-2.1.4.min.js"></script>
</head>
<body>
	<form id="form" action="" method="post">
		<input type="text" id="username"> <br>
		<input type="password" id="password"> <br>
		<input type="button" id="btn" value="登录">
	</form>

<script>
$(document).ready(function(){
	$("#btn").click(function(){
	   var name = $("#username").val();
	   var pwd = $("#password").val()
	   $.post("login.do?method=1", //利用ajax发起请求,这里写servlet的路径
				 {"username":name,"password":pwd},   //传参
				 function(data){    //请求成功时的回调函数
		             if(data.IsOK == true){  
		            	  window.location.href="login.do?method=2"; //如果返回的IsOK的值为true,也就是用户名密码都正确,则执行该跳转
		             }else{
		            	 window.location.href="http://www.baidu.com";
		             }
		          	},
				"json"	
		);
	})	
})
</script>
</body>
</html>


如果实在看不懂,可以尝试下载我的project,去运行,需要说明的是,我建立该工程的环境是tomcat 9

下载地址:http://download.csdn.net/detail/a13432421434/9819642

当然,用ajax提交表单比一般的表单提交代码量多那么一点,至于两种方式提交的区别,还是这里比较有说服力:http://www.cnblogs.com/zhujiabin/p/4901167.html


  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 AJAX 提交表单数据后台可以避免页面的重载,提升用户体验。下面是一个简单的示例代码: HTML 表单: ```html <form id="myForm"> <input type="text" name="username"> <input type="password" name="password"> <button type="submit">提交</button> </form> ``` JavaScript 代码: ```javascript $("#myForm").submit(function(event) { // 阻止表单的默认提交行为 event.preventDefault(); // 使用 AJAX 提交表单数据后台 $.ajax({ url: "submit_form.php", // 提交表单数据的 URL type: "POST", // 提交表单数据的方法 data: $(this).serialize(), // 要提交表单数据 success: function(response) { // 提交成功后的回调函数 console.log("提交成功:" + response); }, error: function(xhr, status, error) { // 提交失败后的回调函数 console.log("提交失败:" + error); } }); }); ``` 在上面的示例代码中,我们使用了 jQuery 提供的 `submit` 方法来监听表单提交事件。当用户点击提交按钮时,我们使用 `event.preventDefault()` 阻止表单的默认提交行为,然后使用 AJAX 提交表单数据后台。其中,`url` 参数指定了提交表单数据的 URL,`type` 参数指定了提交表单数据的方法(这里使用了 POST 方法),`data` 参数指定了要提交表单数据,`success` 参数指定了提交成功后的回调函数,`error` 参数指定了提交失败后的回调函数。在实际使用中,需要根据自己的需求来修改这些参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值