---
title: "ajax的helloworld（1）"
author: "itgo"
date: "2014-06-17T15:15:25Z"
tags: []
categories: ["编程语言"]
slug: "ajax-helloworld-1"
draft: false
lastmod: "2014-06-17T16:31:15Z"
id: 2081693
url: "https://itgo.iteye.com/blog/2081693"
---

本文的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来返回信息给前台。