jquery 自动实现autocomplete+ajax

来公司也差不多一个半月了,一直做点小东西,现在在做公司的出货系统,也只是做来锻炼锻炼的。

好了 不废话了 下面是实现 jquery插件 autocomplete+ajax 自动实现。也是刚学,勿喷。

效果如下:

 

InCustomer.aspx

 1 <html xmlns="http://www.w3.org/1999/xhtml">

 2 <head id="Head1" runat="server">

 3     <title></title>

 4     <link href="css/Style.css" rel="stylesheet" type="text/css" />

 5     <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

 6 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

 7 <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

 8 <script type="text/javascript">

 9    function sele_id(obj) {

10        if (obj.value.length >= 2) {                                //因为我是根据input值改变而触发事件的,但找到的jq插件里面是规定要两个字符或以上才能触发                              

11            $.ajax({                                                //autocomplete这个插件的,所以我在这里判断一下字符长度为2或以上就执行
12 type: "get", 13 url: "ajax/SelectCustomID.ashx?comp=" + obj.value, //是在这个路径下的文件处理逻辑并返回数据 14 success: function (data) { 15 var datas = data.split(","); 16 $("#select_id").autocomplete({ 17 source: datas 18 }); 19 }, 20 Error: function (err) { 21 alert(err); 22 } 23 }); 24 } 25 } 26 </script> 27 </head> 28 <body> 29 <form> 30 <input id="select_id" type="text" oninput="sele_id(this)" runat="server" /> 31 </form> 32 </body>

 

SelectCustomID.ashx

 1 <%@ WebHandler Language="C#" Class="SelectCompany" %>

 2 

 3 using System;

 4 using System.Web;

 5 using i_salesDAL;

 6 using System.Data;

 7 

 8 public class SelectCompany : IHttpHandler {

 9     

10     public void ProcessRequest (HttpContext context) {

11         context.Response.ContentType = "text/plain";

12         //根据传过来的CustomerID 模糊匹配出相关联的

13         string com = context.Request.QueryString["comp"].ToString();

14         string sql = "select CustomerID from custom where CustomerID like '%" + com + "%'";

15         //取得模糊查询的数据源

16         DataTable dt = new DataTable();

17          dt= DBHelper.GetDataSet(sql);

18         //回传数据源

19         string data="";

20         int i;

21         for (i = 0; i < dt.Rows.Count; i++)

22         {

23             //往字符串中添加数据并用,号隔开

24             data += dt.Rows[i][0] + ",";

25         }

26         context.Response.Write(data);

27     }

28  

29     public bool IsReusable {

30         get {

31             return false;

32         }

33     }

34 

35 }

上面是有个dbhelp

这样就可以实现啦,因为没有修改js文件,所以很多限制都是有的。有兴趣的可以自己改下js css 这样就可以达到自己想要的效果啦。

 

你可能感兴趣的:(autocomplete)