【转】用AJAX实现google输入自动完成的简单模拟

作者: harde 分类: DotNet,JavaScript 发布时间: 2009-05-01 00:48

本文转载自:http://www.vs2005.com/Ajax/a427p1.aspx

比较简单的模拟,文本框输入CompanyName,然后
搜索SqlServer2000 里NorthWind数据库 Suppliers表的CompanyName字段,
然后实现自动完成

四个文件
1 .AutoComplete.htm

[html4ts” collapse=”true” line=”1 ]



输入自动完成



CompanyName



[/html4ts" collapse="true" line="1]

AutoComplete.aspx
[csharp" line="1 collapse="true"]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoComplete.aspx.cs" Inherits="AJAXBaseHome.AutoComplete" %>

[/csharp" line="1]

AutoComplete.aspx.cs
[csharp" line="1 collapse="true"]
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Text;
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 System.Web.Configuration;

namespace AJAXBaseHome
{
public partial class AutoComplete : System.Web.UI.Page
{
private static string conString = WebConfigurationManager.ConnectionStrings["myData"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
string input = GetInput();
Response.Write(GetCompanyName(input));
}

//获取输入的字符串
private string GetInput()
{
Stream s = Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}

return builder.ToString();
}

private string GetCompanyName(string input)
{
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand command = new SqlCommand("select * from suppliers where CompanyName like @Name", con);
command.Parameters.Add(new SqlParameter("@name", input + "%"));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.GetXml();
}
}
}
}

[/csharp" line="1]
xslt文件 用于显示xml数据
[xml" line="1" collapse="true" line="1 ]









[/xml" line="1" collapse="true" line="1]

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

一条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注