两种不同的方式 注意参数
不同方法 能提交的参数不一样
Ajax只传term
WebService 传了str tb3 两个参数
关键代码
<script language="javascript" type="text/javascript"> $(function() { $("#txtTest").autocomplete({ minLength: 1, source: function(request, response) { $.ajax({ url: "./Handler.ashx", dataType: "json", data: request, success: function(data) { response(data); alert(data); $('#it').val(data); } }); } }); $('#it').autocomplete({ minLength: 1, source: function(request, response) { $.ajax({ url: "WebService2.asmx/GetData", datatype: "json", data: "{ 'str': '" + request.term + "','tb3':'" + $('#txtTest').val() + "' }", type: "POST", contentType: "application/json", success: function(db) { response($.map(db.d, function(val) { return { value: val } })) }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); } }); }); </script> <form id="form1" runat="server"> <div> <input id="txtTest" type="text" style="80%;" /> </div> <div> <input type="button" id="ib" value="ib" style="129px;"/> <input type="text" id="it" style="80%;" /> </div> </form>
关键代码
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Data; using System.Text; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.Write(GetData(context.Request["term"])); } public bool IsReusable { get { return false; } } private string GetData(string str) { string sql = " select name from htgl.tb_address where name like '%" + str + "%'"; DataTable dt = HFKC.PublicClass.DataBaseOperate.GetTable(sql); StringBuilder sb = new StringBuilder(); if (dt.Rows.Count == 0) return "[]"; sb.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { sb.Append("\"" + dt.Rows[i][0] + "\""); if (i == dt.Rows.Count - 1) sb.Append("]"); else sb.Append(","); } return sb.ToString(); }
关键代码
<%@ WebService Language="C#" Class="WebService2" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Text; using System.Collections.Generic; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class WebService2 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "HelloWorld"; } [WebMethod] public List<string> GetData(string str,string tb3) { List<string> ls = new List<string>(); string sql = " select name from htgl.tb_address where name like '%" + str + "%'"; //string sql = " select name from htgl.tb_address"; DataTable dt = HFKC.PublicClass.DataBaseOperate.GetTable(sql); for (int i = 0; i < dt.Rows.Count; i++) { ls.Add(dt.Rows[i][0].ToString()); } return ls; } }