第二章:Ajax

1、Ajax:异步请求,也就是在不刷新页面的情况向服务器发送请求;客户端与服务端交互数据,需要发送请求(http);
2、ajax一般运用在注册或则登录的时候进行信息提示;也就是在网页不重新加载的情况进行了一次客户端与服务端的数据交互;一般情况服务端(servlet)返回的是一个json类型的数据;
3、示例代码如下:
AjaxServlet类:

package com.jh.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		String username = req.getParameter("username");
		System.out.println("Ajax++++++++"+username);
		//服务器向浏览器响应一个json串,code值只是一个标示,1代表验证成功,0代表不成功;
		String rel = "{\"code\":\"1\"}";
		PrintWriter w = resp.getWriter();
		if(username.matches("^[A-Za-z]+$")&&username.length()>3) {
			w.write(rel);
		}else {
			rel = "{\"code\":\"0\"}";
			w.write(rel);	
		}
		w.flush();
		w.close();
		
		
	}
}

ajax.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script src="js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function(){
	//失去焦点事件
	$("#user").blur(function(){
		/**
		 jquery ajax:$.get(url, [data], [callback], [type])
		 参数:
			 第一个参数url:代表收件人,异步发送请求的路径
			 第二个参数data:发送请求的数据,信的内容
			 第三个参数:回调函数,响应的内容
			 第四个参数type:默认的是text字符串  xml html json
		 */
		
	      $.get(
				 "${pageContext.request.contextPath }/AjaxServlet",
				 {"username":$("#user").val()},
		 		 //响应的函数(内容)
		 		 function(data){
					 var code=data.code;
					 if(code == 0){
						 $("#text").html("此用户名不合法,请更换一个.");
						 console.log("此用户名不合法,请更换一个.");
					 }else{
						 $("#text").html("用户名可以使用.");
						 console.log("用户名可以使用.");
					 }
				 },
				 //type:默认是字符串
				 "json"
		 );

});	
})		
 
</script>
</head>
<body>
<form action="registServlet" method="get">
<table class="tab">
	<tr>
		<td><lable for="username">用户名</lable></td>
		<td><input type="text" id="user"name="username"><span id="text" style="color:red"></span></td>	
	</tr>
	<tr>
		<td><lable for="password">密码</lable></td>
		<td><input type="password" id="password"></td>
		<td id="tips2"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="注册"></td>
	</tr>
</table>
</form>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值