Ajax的简单使用

简介

GET和POST请求

ajax_demo01.jsp

ajax_demo01Servlet.java

ajax_demo02servlet.java

结果

点击get请求的链接

点击post请求的链接

校验用户名是否存在

数据库

ajax_demo02.jsp

UserDao.java

UserDaoImpl.java

CheckUsernameServlet.java

运行结果


简介

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

GET和POST请求

ajax_demo01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!-- 
	发送Ajax的get和post请求,并且接收服务器传回来的数据 
-->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//创建XMLHttpRequest对象
	function ajaxFunction() {
		var xmlHttp;
		try { // Firefox, Opera 8.0+, Chrome, Safari, IE7+
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			try {// Internet Explorer
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
				}
			}
		}
		return xmlHttp;
	}

	//执行get请求
	function get() {
		//1. 创建xmlhttprequest 对象
		var request = ajaxFunction();

		//2. 发送请求。
		/*	
			参数一: 请求类型  GET or  POST
			参数二: 请求的路径
			参数三: 是否异步, true  or false
		 */
		//request.open("GET", "ajax_demo01servlet", true);
		request.open("GET", "ajax_demo01servlet?name=zhujunwei&age=18", true);
		request.send();

		//3.接收响应
		request.onreadystatechange=function(){
			if (request.readyState==4 && request.status==200){
		    	alert(request.responseText);
		    }
		}
	}
	
	//执行post请求
	function post() {
		//1. 创建xmlhttprequest 对象
		var request = ajaxFunction();

		//2. 发送请求。
		request.open("POST", "ajax_demo02servlet", true);
		
		//提交表单数据
		request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		request.send("name=zhujunwei&age=18");

		//3.接收响应
		request.onreadystatechange=function(){
			if (request.readyState==4 && request.status==200){
		    	alert(request.responseText);
		    }
		}
	}
</script>
</head>
<body>
	<h3><a href="#" onclick="get()">使用Ajax方式发送Get请求</a></h3><br>
	<h3><a href="#" onclick="post()">使用Ajax方式发送Post请求</a></h3>
</body>
</html>

ajax_demo01Servlet.java

package com.zhujunwei.servlet;

import java.io.IOException;
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("/ajax_demo01servlet")
public class ajax_demo01servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收参数
		System.out.println("收到了一个GET请求。");
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		String get = "name="+name+"&age="+age ;
		System.out.println(get);
		//响应
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("收到了请求:"+get);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

ajax_demo02servlet.java

package com.zhujunwei.servlet;

import java.io.IOException;
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("/ajax_demo02servlet")
public class ajax_demo02servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//接收参数
		System.out.println("收到了一个POST请求。");
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		String get = "name="+name+"&age="+age ;
		System.out.println(get);
		//响应
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("收到了请求:"+get);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

结果

点击get请求的链接

点击post请求的链接

校验用户名是否存在

数据库

ajax_demo02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!-- 
	ajax用户名的校验
-->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//创建XMLHttpRequest对象
	function ajaxFunction() {
		var xmlHttp;
		try { // Firefox, Opera 8.0+, Chrome, Safari, IE7+
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			try {// Internet Explorer
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
				}
			}
		}
		return xmlHttp;
	}

	//检查用户名是否存在
	function checkUserName() {
		//取得用户名
		var username = document.getElementById("username").value;
		//1. 创建xmlhttprequest 对象
		var request = ajaxFunction();

		//2. 发送请求。
		request.open("POST", "CheckUsernameServlet", true);
		
		//提交表单数据
		request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		request.send("username="+username);

		//3.接收响应
		request.onreadystatechange=function(){
			if (request.readyState==4 && request.status==200){
				var data = request.responseText;
				if(data == 1){
					document.getElementById("span01").innerHTML = "<font color='red'>用户名存在!</font>";
				}else{
					document.getElementById("span01").innerHTML = "<font color='green'>用户名不存在!</font>";
		   		}
			}
		}
	}
</script>
</head>
<body>
	<table border="1" width="500">
		<tr>
			<td>用户名:</td>
			<td><input type="text" name="username" id="username" onblur="checkUserName()"/><span id="span01"></span></td>
		</tr>
		<tr>
			<td>密码:</td>
			<td><input type="password" name="password"/></td>
		</tr>
	</table>
</body>
</html>

UserDao.java

package com.zhujunwei.dao;

public interface UserDao {
	public boolean checkUserName(String username);
}

UserDaoImpl.java

package com.zhujunwei.daoImpl;

import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zhujunwei.dao.UserDao;
import com.zhujunwei.util.CommonCRUDUtil;

public class UserDaoImpl implements UserDao	{

	@Override
	public boolean checkUserName(String username) {
		String sql = "select count(*) from user where username =?";
		Long result = (Long) CommonCRUDUtil.query(sql, new ScalarHandler<Object>(), username);
		return result>0;
	}

}

CheckUsernameServlet.java

package com.zhujunwei.servlet;

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

import com.zhujunwei.dao.UserDao;
import com.zhujunwei.daoImpl.UserDaoImpl;

/**
 * 检查用户名是否存在的servlet
 * @author zhujunwei
 * 2019年2月7日 上午11:23:30
 */
@WebServlet("/CheckUsernameServlet")
public class CheckUsernameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. 检测是否存在
		String username = request.getParameter("username");
//		System.out.println("username="+username);
		
		UserDao dao = new UserDaoImpl();
		boolean isExist = dao.checkUserName(username);
		//2.  通知页面,到底有还是没有。
		if(isExist){
			response.getWriter().println(1);  //存在用户名
		}else{
			response.getWriter().println(2); //不存在该用户名
		}
	}	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

运行结果

posted @ 2019-02-07 20:02  雨中遐想  阅读(2)  评论(0编辑  收藏  举报  来源