解析ajax實現無刷新驗證用戶名是否存在_AJAX教程

      編輯Tag賺U幣
      教程Tag:暫無Tag,歡迎添加,賺取U幣!

      推薦:揭秘Ajax 及其入門基礎
      一、白話Ajax的原理 這個可以從 C/S 和 B/S 的原理說起。Windows操作系統的誕生,為單機通信提供了很大的支持,程序設計也從早期DOS的單任務單用戶向網絡的分布式應用過度。C/S提供的客戶/服務器編程模式為網絡應用提供了一個有效的通信手段。瀏覽器與Web服

      實現用的是jdbc+jsp+servlet,數據庫用的是mysql

      表就2個字段

      實現原理獲得text的值后,通過調用servlet查詢數據庫里是否存在,在通過xml傳到前臺

      OperationName.java

      response.setContentType("text/xml;charset=UTF-8")這句很重要,沒有他前臺獲得不到xml,之前做的時候沒有加

      所以前臺獲得不到xml

      package servlet;

      import java.io.IOException;
      import java.io.PrintWriter;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.ResultSet;
      import java.sql.Statement;
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
      import java.util.List;

      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      public class OperationName extends HttpServlet
      {

      /** *//**
      * Constructor of the object.
      */
      public OperationName()
      {
      super();
      }

      /** *//**
      * Destruction of the servlet. <br>
      */
      public void destroy()
      {
      super.destroy(); // Just puts "destroy" string in log
      // Put your code here
      }

      /** *//**
      * The doGet method of the servlet. <br>
      *
      * This method is called when a form has its tag value method equals to get.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
      String names = request.getParameter("names");
      Collection students = null;
      Connection con = null;
      Statement st = null;
      ResultSet rs = null;
      try
      {
      Class.forName("org.gjt.mm.mysql.Driver");
      con = DriverManager.getConnection("jdbc:mysql:"+
      "//127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=GBK","root","eetrust");
      st = con.createStatement();
      rs = st.executeQuery("select count(*) from test where name='"+names+"'");
      StringBuffer result = new StringBuffer();
      result.append("<OperationNames>");
      System.out.println(result);
      while(rs.next())
      {
      int num = rs.getInt(1);
      result.append("<OperationName>" + num + "</OperationName>");
      }
      result.append("</OperationNames>");
      String responseHtml = result.toString();
      response.setCharacterEncoding( "UTF-8");
      response.setContentType("text/xml;charset=UTF-8");
      response.setHeader("Pragma","No-cache");
      response.setHeader("Cache-Control","no-cache");
      response.setDateHeader("Expires", 0);
      response.getWriter().write(responseHtml);
      }catch(Exception e)
      {
      e.printStackTrace();
      }finally
      {
      try
      {
      rs.close();
      st.close();
      con.close();
      }catch(Exception e)
      {
      e.printStackTrace();
      }
      }
      }

      /** *//**
      * The doPost method of the servlet. <br>
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
      this.doGet(request,response);
      }

      /** *//**
      * Initialization of the servlet. <br>
      *
      * @throws ServletException if an error occure
      */
      public void init() throws ServletException
      {
      // Put your code here
      }

      }
      index.jsp

      ajax("servlet/OperationName?names=" + newOperationName + "&form=form1");"&form=form1"可去掉

      <%@ page language="java" contentType="text/html;charset=GBK"%>
      <%
      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>
      <base href="<%=basePath%>">

      <title>My JSP 'MyJsp.jsp' starting page</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 language="javascript">
      <!--
      function ajax(url){
      if (window.ActiveXObject) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }else if(window.XMLHttpRequest){
      xmlHttp = new XMLHttpRequest();
      }
      xmlHttp.onreadystatechange = processResponse;
      xmlHttp.open("GET",url,true);
      xmlHttp.send(null);
      }
      function processResponse(){
      if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){
      if(xmlHttp.status==200)
      {
      var result = xmlHttp.responseXML;
      var operationName = result.getElementsByTagName("OperationName");
      if(operationName[0].firstChild.nodeValue == "0"){
      document.all.ShowInfo.innerHTML = "<B>不存在<B>";
      }else{
      //alert(22222);
      document.all.ShowInfo.innerHTML = "<B>存在<B>";
      }
      //document.all.ShowInfo.innerHTML = "<font color="red">*</font>";

      }
      return true;
      }
      }
      function aaa()
      {
      var newOperationName = document.all.names.value;
      ajax("servlet/OperationName?names=" + newOperationName + "&form=form1");
      }
      -->
      </Script>
      </head>

      <body>
      <form action="index.jsp" >
      <table>
      <tr>
      <td>
      <input type="text" name="names" value="" Onblur="aaa()">
      </td>
      </tr>
      <tr>
      <TD bgcolor="#EEEEEE" id="ShowInfo">
      asdas
      </TD>
      </tr>
      <tr>
      <!--input type="button" onclick="aaa();" value="提交"-->
      </tr>
      </table>
      </form>
      </body>
      </html>

      web.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app version="2.4"
      xmlns="http://java.sun.com/xml/ns/j2ee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
      <servlet>
      <servlet-name>OperationName</servlet-name>
      <servlet-class>servlet.OperationName</servlet-class>
      </servlet>

      <servlet-mapping>
      <servlet-name>OperationName</servlet-name>
      <url-pattern>/servlet/OperationName</url-pattern>
      </servlet-mapping>
      </web-app>

       

       

      分享:揭秘Ajax 及其入門基礎(續)
      四、常見Ajax編程框架 既然上述Ajax框架已經能工作了,為什么還有那么多的框架呢? 隨著頁面的復雜,可能需要書寫大量的Javascript腳本來對頁面中的DOM對象進行控制,工作量和復雜度會大大增加。Ajax編程框架通常利用面向對象的方法,對一些基本的對象和行為

      來源:模板無憂//所屬分類:AJAX教程/更新時間:2010-01-09
      相關AJAX教程