搜索智能感知效果(調用數據庫數據)

---------------------aspx頁面-前臺------------------------------

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/Jquery1.7.js" type="text/javascript"></script>
    <script src="js/jquery.autocomplete.js" type="text/javascript"></script>
    <script src="js/jquery.autocomplete.pack.js" type="text/javascript"></script>
    <link href="js/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
      <script type="text/javascript">
          $(function () {
              $.ajax({
                  type: "post",
                  contentType: "application/json",
                  url: "WebService1.asmx/GetGoods",
                  data: "{}",
                  success: function (result) {
                      var array = new Array();
                      for (var i = 0; i < result.d.length; i++) {
                          array.push(result.d[i]);
                      }
                      $('#txtQuery').autocomplete(array);
                  }
              })
          })
    </script>


</head>
<body>
      <form id="form1" runat="server">
    <div>
        <input type="text" id="txtQuery" />
    </div>
    </form>


</body>
</html>

--------------------------- WebServices-------------------------------------

// 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的註釋。

    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public List<string> GetGoods()
        {
            List<string> list = null;
            if (Context.Cache["goods"] == null)
            {
                string strcon = ConfigurationManager.ConnectionStrings["sqlservercon"].ConnectionString;
                SqlConnection conn = new SqlConnection(strcon);
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select GoodsTitle FROM T_Search";
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                list = new List<string>();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        list.Add(reader["GoodsTitle"].ToString());
                    }
                }
                reader.Dispose();
                cmd.Dispose();
                conn.Dispose();
                Context.Cache["goods"] = list;
            }
            else
            {
                list = Context.Cache["goods"] as List<string>;
            }


            return list;
        } 

    }

-----------------------Web.config--------------------------------

<connectionStrings>
    <add name="sqlservercon" connectionString="Data Source=.;Initial Catalog=lianxi;Persist Security Info=True;User ID=sa;Password=111111"/>
    
  </connectionStrings>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章