仿Google suggest的一段代码
这两天做了个类似Google suggest的搜索功能的Ajax代码,当然这段代码是在AJAX基础教程中示例4.9的基础上修改完成的.
效果图:

先把代码贴出来,大家一起学习研究.其中一些数据连接方面的,就不介绍了,相信大家已经对这个没有什么问题了
-----------AdvSearch.aspx-------------------------------------------------------------------------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<style type="text/css">
body
{
font-size:12px;
}
.mouseOut
{
font-size:12px;
background: #708090;
color: #FFFAFA;
}

.mouseOver
{
font-size:12px;
background: #FFFAFA;
color: #000000;
}

</style>
<script type="text/javascript" language="javascript">
function selDate()
{
var dataString = showModalDialog("/public/js/SelectDate.htm", "yyyy-mm-dd" ,"dialogWidth:286px;dialogHeight:240px;status:no;help:no;menu:no");
document.getElementById("<%=txtBeginDate.ClientID%>").value = dataString ;
}

function selDate2()
{
var dataString = showModalDialog("/public/js/SelectDate.htm", "yyyy-mm-dd" ,"dialogWidth:286px;dialogHeight:240px;status:no;help:no;menu:no");
document.getElementById("<%=txtEndDate.ClientID%>").value = dataString ;
}
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
var flag=false;

function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function setflag(){
flag = true;
}
function DisSelect()
{
if(flag==false)
document.getElementById("popup").style.display="none";
}

function initVars() {
inputField = document.getElementById("names");
nameTable = document.getElementById("name_table");
completeDiv = document.getElementById("popup");
nameTableBody = document.getElementById("name_table_body");
document.getElementById("popup").style.display="block";
}

function findNames() {
initVars();
if (inputField.value.length > 0) {
createXMLHttpRequest();
var url = "AdvSearchAjax.aspx?names=" + escape(inputField.value);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
} else {
clearNames();
}
}

function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200)
{
try
{
var name = xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.data;
}
catch(e)
{
document.getElementById("popup").style.display="none";
clearNames();
}
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
}
else if (xmlHttp.status == 204)
{
clearNames();
}
}
}
function setNames(the_names) {
clearNames();
var size = the_names.length;
setOffsets();

var row, cell, txtNode;
for (var i = 0; i < size; i++) {
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");
cell.onmouseout = function() {this.className='mouseOver';flag=false;};
cell.onmouseover = function() {this.className='mouseOut';flag=true;};
cell.setAttribute("bgcolor", "#FFFAFA");
cell.setAttribute("border", "0");
//cell.setAttribute("onmouseover", "setflag()");
cell.onclick = function() { populateName(this); } ;

txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}

function setOffsets() {
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;

completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width="600px";
}
function calculateOffsetLeft(field) {
return calculateOffset(field, "offsetLeft");
}

function calculateOffsetTop(field) {
return calculateOffset(field, "offsetTop");
}

function calculateOffset(field, attr) {
var offset = 0;
while(field) {
offset += field[attr];
field = field.offsetParent;
}
return offset;
}

function populateName(cell) {
inputField.value = cell.firstChild.nodeValue;
clearNames();
}

function clearNames() {
var ind = nameTableBody.childNodes.length;
for (var i = ind - 1; i >= 0 ; i--) {
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
function gotoSearch()
{
var productType =document.getElementById("productType");
var p_Brand =document.getElementById("p_Brand");
p_Brand
alert(p_Brand.value);
}
</script>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 972px">
<tr>
<td>品牌</td>
<td><asp:DropDownList ID="p_Brand" runat="server" CssClass="Text">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>产品名称:</td>
<td><input type="text" size="20" id="names" onkeyup="findNames();" onblur="DisSelect();" style="height:20;"/>
<div style="position:absolute;top:0;left:0;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</td>
</tr>
<tr>
<td>商品编号:</td>
<td><asp:TextBox ID="p_ID" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>支付方式</td>
<td><asp:CheckBoxList ID="p_PayMethod" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>EMS</asp:ListItem>
<asp:ListItem>货到付款</asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
<tr>
<td>价格范围:</td>
<td><asp:TextBox ID="p_PriceL" runat="server"></asp:TextBox> ~<asp:TextBox ID="p_PriceH" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>上架时间:</td>
<td><asp:TextBox ID="txtBeginDate" runat="server" Width="65px"></asp:TextBox><button onclick="selDate()" class="btnDefault">
</button> 到 <asp:TextBox ID="txtEndDate" runat="server" Width="65px"></asp:TextBox><button onclick="selDate2()" class="btnDefault">
</button></td>
</tr>
<tr>
<td>是否需要运输费用:</td>
<td><asp:RadioButtonList ID="p_IsNeedfee" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="True">不限</asp:ListItem>
<asp:ListItem>是</asp:ListItem>
<asp:ListItem>否</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btn_Search" runat="server" Text="搜 索" OnClientClick="gotoSearch();" /></td>
</tr>

</table>
</div>
</form>
</body>
</html>
=======AdvSearchAjax.aspx=========================================================================================
在aspx页面中 这个页面中只保留第一行 其余的html代码全部去掉,关键是后台cs文件中的处理
AdvSearchAjax.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CNTVS.TOOLS.COMM;
using CNTVS.TOOLS.SQLDB;
using System.Text;

public partial class Public_Product_AdvSearchAjax : System.Web.UI.Page
{
DataBase db = new DataBase();
SqlConnection conn = null;

protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/xml"; //设置输出的格式为XML
Response.Charset = "UTF-8"; //设置输出的编码为UTF-8
this.GetXmlData();
}


private void GetXmlData()
{ //这是用来获取下拉列表框中下面提示的项目数据,获取的数据用XML格式输出
conn = db.GetConn();
string names = Request.QueryString["names"];
StringBuilder xmlData = new StringBuilder();
xmlData.AppendLine(@"<?xml version='1.0' encoding='UTF-8' ?>");
xmlData.AppendLine(@"<response>");
string sql = "";
sql = "select F_Name from T_Product where F_Name like '%" + names + "%'";
SqlDataReader sdr = db.RunSql(sql, conn);
while (sdr.Read())
{
xmlData.AppendLine(@"<name>" + sdr["F_Name"].ToString() + "</name>");
}
sdr.Close();
conn.Close();
xmlData.AppendLine(@"</response>");
Response.Write(xmlData.ToString());
}
}
这两个页面就能完成类似Google suggest的功能 ,当然这样的版本比较简单 ,但是也能看到一点Ajax带来的新功能了.
效果图:

先把代码贴出来,大家一起学习研究.其中一些数据连接方面的,就不介绍了,相信大家已经对这个没有什么问题了
-----------AdvSearch.aspx-------------------------------------------------------------------------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<style type="text/css">
body
{
font-size:12px;
}
.mouseOut
{
font-size:12px;
background: #708090;
color: #FFFAFA;
}
.mouseOver
{
font-size:12px;
background: #FFFAFA;
color: #000000;
}
</style>
<script type="text/javascript" language="javascript">
function selDate()
{
var dataString = showModalDialog("/public/js/SelectDate.htm", "yyyy-mm-dd" ,"dialogWidth:286px;dialogHeight:240px;status:no;help:no;menu:no");
document.getElementById("<%=txtBeginDate.ClientID%>").value = dataString ;
}
function selDate2()
{
var dataString = showModalDialog("/public/js/SelectDate.htm", "yyyy-mm-dd" ,"dialogWidth:286px;dialogHeight:240px;status:no;help:no;menu:no");
document.getElementById("<%=txtEndDate.ClientID%>").value = dataString ;
}
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
var flag=false;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function setflag(){
flag = true;
}
function DisSelect()
{
if(flag==false)
document.getElementById("popup").style.display="none";
}
function initVars() {
inputField = document.getElementById("names");
nameTable = document.getElementById("name_table");
completeDiv = document.getElementById("popup");
nameTableBody = document.getElementById("name_table_body");
document.getElementById("popup").style.display="block";
}
function findNames() {
initVars();
if (inputField.value.length > 0) {
createXMLHttpRequest();
var url = "AdvSearchAjax.aspx?names=" + escape(inputField.value);
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
} else {
clearNames();
}
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200)
{
try
{
var name = xmlHttp.responseXML.getElementsByTagName("name")[0].firstChild.data;
}
catch(e)
{
document.getElementById("popup").style.display="none";
clearNames();
}
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
}
else if (xmlHttp.status == 204)
{
clearNames();
}
}
}
function setNames(the_names) {
clearNames();
var size = the_names.length;
setOffsets();
var row, cell, txtNode;
for (var i = 0; i < size; i++) {
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");
cell.onmouseout = function() {this.className='mouseOver';flag=false;};
cell.onmouseover = function() {this.className='mouseOut';flag=true;};
cell.setAttribute("bgcolor", "#FFFAFA");
cell.setAttribute("border", "0");
//cell.setAttribute("onmouseover", "setflag()");
cell.onclick = function() { populateName(this); } ; 
txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}
function setOffsets() {
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;
completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width="600px";
}
function calculateOffsetLeft(field) {
return calculateOffset(field, "offsetLeft");
}
function calculateOffsetTop(field) {
return calculateOffset(field, "offsetTop");
}
function calculateOffset(field, attr) {
var offset = 0;
while(field) {
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
function populateName(cell) {
inputField.value = cell.firstChild.nodeValue;
clearNames();
}
function clearNames() {
var ind = nameTableBody.childNodes.length;
for (var i = ind - 1; i >= 0 ; i--) {
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
function gotoSearch()
{
var productType =document.getElementById("productType");
var p_Brand =document.getElementById("p_Brand");
p_Brand
alert(p_Brand.value);
}
</script>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 972px">
<tr>
<td>品牌</td>
<td><asp:DropDownList ID="p_Brand" runat="server" CssClass="Text">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>产品名称:</td>
<td><input type="text" size="20" id="names" onkeyup="findNames();" onblur="DisSelect();" style="height:20;"/>
<div style="position:absolute;top:0;left:0;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</td>
</tr>
<tr>
<td>商品编号:</td>
<td><asp:TextBox ID="p_ID" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>支付方式</td>
<td><asp:CheckBoxList ID="p_PayMethod" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>EMS</asp:ListItem>
<asp:ListItem>货到付款</asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
<tr>
<td>价格范围:</td>
<td><asp:TextBox ID="p_PriceL" runat="server"></asp:TextBox> ~<asp:TextBox ID="p_PriceH" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>上架时间:</td>
<td><asp:TextBox ID="txtBeginDate" runat="server" Width="65px"></asp:TextBox><button onclick="selDate()" class="btnDefault">
</button> 到 <asp:TextBox ID="txtEndDate" runat="server" Width="65px"></asp:TextBox><button onclick="selDate2()" class="btnDefault">
</button></td>
</tr>
<tr>
<td>是否需要运输费用:</td>
<td><asp:RadioButtonList ID="p_IsNeedfee" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Selected="True">不限</asp:ListItem>
<asp:ListItem>是</asp:ListItem>
<asp:ListItem>否</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btn_Search" runat="server" Text="搜 索" OnClientClick="gotoSearch();" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>=======AdvSearchAjax.aspx=========================================================================================
在aspx页面中 这个页面中只保留第一行 其余的html代码全部去掉,关键是后台cs文件中的处理
AdvSearchAjax.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CNTVS.TOOLS.COMM;
using CNTVS.TOOLS.SQLDB;
using System.Text;
public partial class Public_Product_AdvSearchAjax : System.Web.UI.Page
{
DataBase db = new DataBase();
SqlConnection conn = null;
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/xml"; //设置输出的格式为XML
Response.Charset = "UTF-8"; //设置输出的编码为UTF-8
this.GetXmlData();
}

private void GetXmlData()
{ //这是用来获取下拉列表框中下面提示的项目数据,获取的数据用XML格式输出
conn = db.GetConn();
string names = Request.QueryString["names"];
StringBuilder xmlData = new StringBuilder();
xmlData.AppendLine(@"<?xml version='1.0' encoding='UTF-8' ?>");
xmlData.AppendLine(@"<response>");
string sql = "";
sql = "select F_Name from T_Product where F_Name like '%" + names + "%'";
SqlDataReader sdr = db.RunSql(sql, conn);
while (sdr.Read())
{
xmlData.AppendLine(@"<name>" + sdr["F_Name"].ToString() + "</name>");
}
sdr.Close();
conn.Close();
xmlData.AppendLine(@"</response>");
Response.Write(xmlData.ToString());
}
}
这两个页面就能完成类似Google suggest的功能 ,当然这样的版本比较简单 ,但是也能看到一点Ajax带来的新功能了.

浙公网安备 33010602011771号