`
itgo
  • 浏览: 2729 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

ajax的helloworld(1)

    博客分类:
  • ajax
 
阅读更多

本文的ajax技术用jquery实现。后台用servlet。

本程序的实现了异步检测用户名在数据库是否已经存在的功能。

第一步:

jsp页面:

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>用户注册</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="<%=path %>/js/index.js"></script>
  </head>
  
  <body>
  <p>欢迎登陆</p>
    <form>
    	用户名:<input type="text" name="userName" id="userName"><span id="userNameHint"></span><br>
    	密&nbsp;&nbsp;码:<input type="password"><br>
    	<input type="submit" value="注册">
    </form>
  </body>
</html>

 一个简单的form表单。一部检测id为userName的输入框。使用id为userNameHit的span来返回提示。

 

第二步:

js:(注:首先要引入jquery)

$(document).ready(function() {
	$("#userName").change(function(){
		$.ajax({
			 url:'RegisterSer',
			 data:{userName:$("#userName").val()},
			 type: "POST",
			 error:function(){
	             alert("error occured!!!");
	         },
	         success:function(data){
	        	 if(data=="true"){
	        		 $("#userNameHint").text("恭喜!账号可用").css({"color":"green"}); 
	        	 }else{
	        		 $("#userNameHint").text("抱歉!该账号已存在").css({"color":"green"}); 
	        	 }
	         }
		})
	});
});

 

 第三步:

新建servlet:RegisterSer

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("hellworld");
		String userName  = request.getParameter("userName");
		if (userName.equals("exist")) {
			response.getWriter().write("false");
		} else {
			response.getWriter().write("true");

		}
	}

 使用response来返回信息给前台。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics