使用jquery的來實現ajax效果,比xmlhttp_request對象使用起來更加方便,更簡潔,下面給出一個列子,首先建立JSP頁面,從外部引入JS檔案。
Code:
- <%@ 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檔案如下:
Code:
- $(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()方法傳過來的值,如下:
Code:
- 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,就能看到效果了。