使用jQuery ajax 验证表单的例子

index.jsp页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<script type="text/javascript" src="/jQuery/jQuery/jquery-1.2.6.pack.js"></script> 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript">
    jQuery(function(){
		$("#user_name").blur(function(){
			var name= $.trim($("#user_name").val());   //获得表单的值.
			$.ajax({
				url:"/jQuery/myServlet", //请求服务器url地址.
				data:{username:name},//获得表单里面的值,传入服务器中..
				cache:false,
				success:function(data){
					if(data=="true"){
						alert("姓名可以使用!");
					}else{
						alert("姓名不能使用!");
					}	
				}
			})
		})
	});	
    </script>
  </head>
  
  <body >
  	<form action="" name="myform">
    		UserName:<input type="text" id="user_name">
    	</form>
  </body>
</html>

 

 

下面这一段是MySerlet代码:

package pack.java.demo.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * MyServlet.
 * @author ZhouHaiTao.
 *
 */
public class myServlet extends HttpServlet {
	private static final long serialVersionUID = 7851121456512273692L;

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得用户名,传过来的用户名,(注意:这个地方不是直接那表单的name,而是拿ajax里面的param里面的name);
		String username=request.getParameter("username");
		PrintWriter writer=response.getWriter();
		if(username.equals("zhouhaitao")){
			writer.print("false");
		}else{
			writer.print("true");
		}
	}
}

 

 

部署完成之后,就能测试,是否成功.. 功能,相当的简单..就是验证用户名是否存在..

你可能感兴趣的:(JavaScript,java,jquery,Ajax,servlet)