ASP.NET中基于jQuery/Ajax的autocomplete文本框不工作如何修复?
ASP.NET WebForm jQuery UI Autocomplete无响应修复方案
1. 解决控件选择器失效问题
ASP.NET中runat="server"的控件默认客户端ID会自动拼接父容器前缀,直接用$("#searchTitle")大概率选不到元素,两种修复方案:
- 方案1:给TextBox控件加
ClientIDMode="Static"属性,强制客户端ID和服务端ID一致:
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle" ClientIDMode="Static"></asp:TextBox>
- 方案2:JS里直接用服务端输出的客户端ID:
$("#<%= searchTitle.ClientID %>").autocomplete({/* 原有配置 */})
2. 修正jQuery API拼写错误
jQuery对参数大小写敏感,现有代码两处拼写错误会导致功能失效:
minlength要改成minLength(首字母L大写)datafilter要改成dataFilter(首字母F大写),如果没有自定义数据过滤逻辑可以直接删掉这行配置
3. 完善Autocomplete请求逻辑
source回调内置了当前输入值request.term,不需要主动获取文本框值,同时建议加error回调方便定位接口问题:
$(function () { $("#searchTitle").autocomplete({ source: function (request,response) { var param = { posting_jobPosition: request.term }; $.ajax({ url: "jobseekerHome.aspx/GetTitles", data: JSON.stringify(param), type: "post", contentType: "application/json; charset=utf-8", success: function (data) { response($.map(data.d, function (item) { return {value: item }})) }, error: function(xhr, err) { console.log("接口请求错误:", err, xhr.responseText); // 打开浏览器控制台可查看报错原因 } }); }, minLength: 1 }); });
4. 补充jQuery UI样式引用
当前只引入了jQuery UI的JS文件,没有引入对应CSS会导致下拉列表渲染后不可见,在页面head中添加样式引用:
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/themes/smoothness/jquery-ui.css" />
5. 后端修复SQL注入风险(必改)
原有代码直接拼接SQL存在严重注入漏洞,改成参数化查询,同时用using自动释放数据库资源:
[WebMethod] public static List<string> GetTitles(string posting_jobPosition) { string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; List<string> Titles = new List<string>(); string query = "SELECT posting_jobPosition FROM BusinessJobPosting WHERE posting_jobPosition LIKE ? AND isActive = true"; using (OleDbConnection Connection = new OleDbConnection(CS)) using (OleDbCommand oleCom1 = new OleDbCommand(query, Connection)) { oleCom1.Parameters.AddWithValue("?", "%" + posting_jobPosition + "%"); Connection.Open(); using (OleDbDataReader reader = oleCom1.ExecuteReader()) { while (reader.Read()) { Titles.Add(reader[0].ToString()); } } } return Titles; }
额外检查项:确认Web.config没有配置权限拦截规则禁止POST请求访问aspx页面的WebMethod方法。
内容的提问来源于stack exchange,提问作者notGoodAtThis
相关产品推荐
相关产品推荐

