jQuery UI Autocomplete 控件简单用法,在PC网站和微信网页中增加读取淘宝数据源

1、在原有控件中增加,最小改动

原有搜索代码:

 <form action='<%linkurl("gsearch")%>'>
                            <input id="keywords" name="keywords" type="text" autocomplete="off" placeholder="请输入商品关键词、淘宝链接或者淘宝商品标题">
                            <button type="submit" class="btn">搜索</button>
                        </form>

 

2、改造后代码

2.1、引用必要文件,点这里打包下载

jquery-ui-1.8.17.custom.css

jquery-1.7.1.min.js

jquery-ui-1.8.17.custom.min.js

jquery-ui-widget-combobox.js

 

2.2、增加控件事件

控件ID为:keywords
$("#keywords").autocomplete({
                source: "remoteJSON.ashx",
                minLength: 2
            });

 

3、读取远端数据

remoteJSON.ashx

<%@ WebHandler Language="C#" Class="remoteJSON" %>

using System;
using System.Web;
using System.Text;
using Newtonsoft;

public class remoteJSON : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // 查询的参数名称默认为term
        string query = context.Request.QueryString["term"];
        StringBuilder builder = new StringBuilder();
        SuguestRoot str = get_Suggect(query);
        builder.Append("[");
        if (str != null)
        {
            for (int i = 0; i < str.result.Count; i++)
            {
                builder.Append("{\"value\":\"");
                builder.Append(str.result[i][0].ToString());
                builder.Append("\",\"label\":\"");
                builder.Append(str.result[i][0].ToString());
                builder.Append("\"},");
            }
        }

        if (builder.Length > 1)
            builder.Length = builder.Length - 1;
        builder.Append("]");

        context.Response.ContentType = "text/javascript";
        context.Response.Write(builder.ToString());
    }
    private SuguestRoot get_Suggect(string q)
    {
        string url = "https://suggest.taobao.com/sug?callback=autocomplete&code=utf-8&q={0}";
        url = string.Format(url, q);
        string s = DTcms.Common.Utils.HttpGet(url);
        SuguestRoot jp = null;
        string str = "";
        try
        {
            str = DTcms.Common.Utils.HttpGet(url);
            str = str.Replace("autocomplete(", "").Replace(")", "");
            jp = (SuguestRoot)Newtonsoft.Json.JsonConvert.DeserializeObject<SuguestRoot>(str);
        }
        catch(Exception ex) {
            //do log 
        }
        return jp;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}

public class SuguestRoot
{
    /// <summary>
    /// Result
    /// </summary>
    public System.Collections.Generic.List<System.Collections.Generic.List<string>> result { get; set; }
}

 

4、效果

 

PC端

微信:

 

posted @ 2017-06-23 15:55  就是打折网  阅读(405)  评论(0)    收藏  举报