waysun一路阳光

不轻易服输,不轻言放弃.--心是梦的舞台,心有多大,舞台有多大。踏踏实实做事,认认真真做人。

  BlogJava :: 首页 :: 新随笔 :: 联系 ::  :: 管理 ::
  167 随笔 :: 1 文章 :: 64 评论 :: 0 Trackbacks
转自:http://hi.baidu.com/mahaibao/blog/item/cf38b1546103011e3b2935c3.html

最近和朋友们一起做了一个搜索提示的功能    使用了ajax+mysql数据库进行的操作,代码贴出来给大家参考一下:

suggest.html:

<html>
<head>
    <style type="text/css" media="screen">
     body {
      font: 11px arial;
     }
     .suggest_link {
      background-color: #FFFFFF;
      padding: 2px 6px 2px 6px;
     }
     .suggest_link_over {
      background-color: #E8F2FE;
      padding: 2px 6px 2px 6px;
     }
     #search_suggest {
         position: absolute;
      background-color: #FFFFFF;
      text-align: left;
      border: 1px solid #000000;   
     }  
    </style>
    <script language="JavaScript" type="text/javascript" src="ajax_search.js"></script>
</head>
<body>
    <h3>Simple AJAX Search Suggest</h3>
    <div style="width: 500px;">
     <form id="frmSearch" action="">
<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
    <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" /><br />
    <div id="search_suggest">
      </div>
     </form>
    </div>
</body>
</html>

 

ajax_search.js文件:


//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
} else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
} else {
    alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
function createAjaxObj(){
    var httprequest=false
    if (window.XMLHttpRequest)
    { // if Mozilla, Safari etc
      httprequest=new XMLHttpRequest()
      if (httprequest.overrideMimeType)
        httprequest.overrideMimeType('text/xml')
     }
     else if (window.ActiveXObject)
     { // if IE
       try {
         httprequest=new ActiveXObject("Msxml2.XMLHTTP");
       }
       catch (e){
         try{
            httprequest=new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (e){}
       }
     }
     return httprequest
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = createAjaxObj();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
    var str = escape(document.getElementById('txtSearch').value);
    searchReq.open("GET", 'search?search=' + str, true);
    searchReq.onreadystatechange = handleSearchSuggest;
    searchReq.send(null);
}  
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
    var ss = document.getElementById('search_suggest')
    ss.innerHTML = '';
    var str = searchReq.responseText.split("\n");
    for(i=0; i < str.length - 1; i++) {
     //Build our element string.    This is cleaner using the DOM, but
     //IE doesn't support dynamically added attributes.
     var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
     suggest += 'onmouseout="javascript:suggestOut(this);" ';
     suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
     suggest += 'class="suggest_link">' + str[i] + '</div>';
     ss.innerHTML += suggest;
    }
}
}

//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
}

 

数据库的代码:


CREATE DATABASE /*!32312 IF NOT EXISTS*/ search;
USE search;


DROP TABLE IF EXISTS SUGGEST;
CREATE TABLE SUGGEST (
    SUGGEST_ID int(11) NOT NULL auto_increment,
    TITLE varchar(255) default NULL,
    PRIMARY KEY    (SUGGEST_ID)
)TYPE=MyISAM ;

LOCK TABLES SUGGEST WRITE;
INSERT INTO SUGGEST VALUES (1,'Home'),(2,'TECHNOLOGIES'),(3,'SOLUTIONS    AND SOFTWARE'),(4,'Websites'),(5,'Web Apps'),(6,'Applications'),(7,'E-COMMERCE SOLUTIONS'),(8,'osCommerce'),(9,'CMS / Portals'),(10,'Microsoft .NET'),(11,'J2EE'),(12,'LAMP'),(13,'PHP'),(14,'MySQL'),(15,'Apache'),(16,'ASP.NET'),(17,'Windows Applications'),(18,'JSP'),(19,'SWING'),(20,'Web Technologies'),(21,'XHTML'),(22,'RSS / ATOM'),(23,'XML'),(24,'XSL'),(25,'XAML'),(26,'AJAX'),(27,'About DynamicAJAX'),(28,'CSS'),(29,'The Basics'),(30,'SAJAX'),(31,'About The Site Images'),(32,'About Me'),(33,'JavaScript'),(34,'RSS 2.0'),(35,'ATOM 1.0'),(36,'Search Engine Optimization'),(37,'Flash'),(38,'Open Source'),(39,'HTTP Server'),(40,'Full Text Search'),(41,'Best Practices'),(42,'XML Schema Definitons'),(43,'Web Content Accessibility Guidelines'),(44,'Printable Pages'),(45,'Search Engine'),(46,'Navigation'),(47,'Direct Web Remoting'),(48,'Mars Exploration Rovers'),(49,'Cassini'),(50,'Fun with Queries'),(51,'SEO Tricks and Tactics'),(52,'osCommerce Contributions'),(53,'PHP & IIS'),(54,'Regular Expressions'),(55,'Rants'),(56,'URL Rewrite'),(57,'Fun with CSS'),(58,'ActionScript'),(59,'Visual Studio 2005'),(60,'SQL Server'),(61,'Search Engine Commands'),(62,'Web Site Layout'),(63,'AJAX'),(64,'AJAX Basics'),(65,'ATLAS'),(66,'SAJAX'),(67,'Tutorials'),(68,'Novice'),(69,'Frameworks'),(70,'Ajax.NET'),(71,'Framework Tutorials'),(72,'SAJAX'),(73,'Ajax.NET'),(74,'Direct Web Remoting'),(75,'Intermediate'),(76,'AJAX Example Sites'),(77,'My Tutorials'),(78,'AJAX Web Chat Part 1'),(79,'The JavaScript'),(80,'Sending The Request'),(81,'Color Schemes'),(82,'AJAX Resources'),(83,'The Backend'),(84,'Usability Additions'),(85,'AJAX Instant Messenger Part 1'),(86,'Ruby on Rails'),(87,'Crazy Queries'),(88,'XmlHttpRequest Methods'),(89,'XmlHttpRequest Properties'),(90,'AjaxTags'),(91,'Direct Web Remoting'),(92,'My URL Rewriting'),(93,'Great Quotes'),(94,'IXSSO Queries'),(95,'AFLAX'),(96,'Other Technologies'),(97,'Microsoft Indexing Server'),(98,'.NET & CISSO');
UNLOCK TABLES;

SearchSuggest.java:

package book.suggest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

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

public class SearchSuggest extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, java.io.IOException {
    String search = request.getParameter("search");//获得请求中cate的值
    //定义查询数据库的SQL语句
    String sql = "select title from suggest where title like '"+search+"%' order by title";

    Connection conn = null;//声明Connection对象
    Statement stmt = null;//声明Statement对象
    ResultSet rs = null;//声明ResultSet对象
    Vector vData = new Vector();
    //response.setContentType("text/xml");//设置返回数据类型为xml格式
    java.io.PrintWriter out = response.getWriter();

    try {
     // 加载数据库驱动类
     Class.forName("com.mysql.jdbc.Driver");
     // 访问数据库的地址
     String url = "jdbc:mysql://localhost/search";
     //创建Connection对象
     conn = DriverManager.getConnection(url, "root", "");
     // 创建Statement对象
     stmt = conn.createStatement();
     // 执行SQL语句,返回记录集
     rs = stmt.executeQuery(sql);
     //定义AblumEO实体对象
     while (rs.next())
     {
      vData.add(rs.getString("TITLE"));
     }
     StringBuffer buf = new StringBuffer();
     for (int i=0;i<vData.size();i++)
     {
      String keyword = (String)vData.get(i);
      buf.append(keyword+"\n");
     }
     out.print(buf.toString());
//     out.print(parasToXML(vData));//调用parasToXML()方法
    } catch (Exception e) {

     e.printStackTrace();

    } finally {//最后关必记录集,Connection对象
     try {
      // this will close any associated ResultSets
      if (stmt != null)
       stmt.close();
      if (conn != null)
       conn.close();
     } catch (SQLException sqle) {
     }
    }
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, java.io.IOException {

    doPost(request, response);
}
/*
public String parasToXML(Vector v) {// 该方法将数据转化成XML格式输出
    StringBuffer buf = new StringBuffer();
    buf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    buf.append("<pictures>");
    for (int i = 0; i < v.size(); i++) {
     AlbumEO album = (AlbumEO) v.get(i);
     buf.append("<item>");
     buf.append("<name>" + album.getAlbumName() + "</name>");
     buf.append("<url>" + album.getAlbumURL() + "</url>");
     buf.append("<description>" + album.getAlbumDescription()
       + "</description>");
     buf.append("</item>");
    }
    buf.append("</pictures>");
    return buf.toString();
}
*/
}

 

本示例共有 四部分,请大家复制到自己的文件中进行 运行,最后的结果如图:

posted on 2008-08-05 15:56 weesun一米阳光 阅读(770) 评论(0)  编辑  收藏 所属分类: AJAX总结备用

只有注册用户登录后才能发表评论。


网站导航: