使用jquery的来实现ajax效果,比xmlhttp_request对象使用起来更加方便,更简洁,下面给出一个列子,首先建立JSP页面,从外部引入JS文件。
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <html>
- <head>
- <title>jquery1.4.2</title>
- <link type="text/css" rel="stylesheet" href="css/login1.css"></link>
- <script type="text/javascript" src="js/jquery-1.4.2.js"></script>
- <script type="text/javascript" src="js/login.js"></script>
- <script type="text/javascript" src="js/loginajax.js"></script>
- </head>
- <body>
- <h1 align="center">用户登录页面</h1>
- <hr color="blue">
- <div align="center">
- <table cellspacing=5 border=5 bodercolor=#ffaa00 >
- <tr><th colspan="3" align="center" bgcolor=#ffaa00>用户登录</th></tr>
- <tr>
- <th rowspan="3" background="images/2.jpg" style="width=90px"></th>
- <td>用户名:</td><td><input class="text" id="usernameID" type="text" value="please input your name" name="username" ><label id="message"></label></td></tr>
- <tr><td>密 码:</td><td><input class="text" id="userpasswordID" value="123456" type="password" name="userpassword" ></td></tr>
- <tr><td colspan="2" align="center"><input name="login" type="submit" value="注册"> <input type="reset" value="重置"></td></tr>
- </table>
- </div>
- </body>
- </html>
建立loginajax.js文件如下:
- $(document).ready(function(){
- //获取lable标签
- var $lable=$("#message");
- //获取文本框的jquery对象
- var $txtUserName=$("#usernameID");
- $txtUserName.click(function(){
- $lable.html("检测用户名中......");
- });
- //失去光标事件
- $txtUserName.blur(function(){
- var $name=$txtUserName.val();
- //使用GER方法传值
- $.get("check?name="+$name,function(data){
- //使用POST方法传值
- //$.post("checkuser.do",{name:$name,name1:$name},function(data){
- //服务器端的返回值显示到页面
- $lable.html(data);
- //alert(data);
- });
- });
- });
最后需要建立servlet来处理jquery中get()方法传过来的值,如下:
- package myclass.serlet;
- 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;
- public class Check extends HttpServlet {
- protected void service(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- PrintWriter out=null;
- out=response.getWriter();
- String name=request.getParameter("name");
- System.out.print(name);
- if("liping".equals(name)){
- out.println("sorry,user name:"+name+" has existed");
- }else{
- out.println("congratulation,user name: "+name+" can use");
- }
- out.flush();
- out.close();
- }
- }
然后,打开tmocat,就能看到效果了。