Ajax小案例

Ajax核心是XMLHttpRequest,明白这个对象的属性(readyState,status,responseText,statusText)以及方法(open,send),事件(onreadystatechange),以及get和post请求就可以写这两个Ajax小案例了。

1.使用Ajax检测用户名是否可以注册

注册jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here



用户名:
密码:

验证注册jsp代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


<%
String name=request.getParameter("name");
boolean flag=true;
if(name.indexOf("suzy")>=0)//用户名包含suzy即用户名被占用(没有用数据库)
{
	flag=false;
}
if(flag)
{
	out.print("用户名可以使用");
}else
{
	out.print("用户名被占用");
}
%>

 

效果:

Ajax小案例_第1张图片

包含suzy即用户名被占用

Ajax小案例_第2张图片

2.使用Ajax根据生日获取相应的名字和地址

birth.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here



生日:
名字:
地址:

BirthServlet代码:(使用map容器添加了一些数据主要用于测试)

package com.suzy.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

/**
 * Servlet implementation class BirthServlet
 */
public class BirthServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BirthServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String birh=request.getParameter("birth");
		Map map=new HashMap<>();
		map.put("0621", "仲夏,西安");
		map.put("0530", "允儿,首尔");
		map.put("1010", "秀智,光州");
		map.put("0611", "新垣结衣,冲绳");
		map.put("0216", "小松菜奈,东京");
		String result=map.get(birh);
		if(result==null)
		{
			result="没有存入,没有存入";
		}
		response.setContentType("text/html; charset=UTF-8");
response.getWriter().println(result);
		
				}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

效果:

Ajax小案例_第3张图片

Ajax小案例_第4张图片

你可能感兴趣的:(java,web学习)