ASP.NET搜索自动补全本地正常,部署至Cpanel后失效求助
ASP.NET搜索自动补全本地正常,Cpanel部署后失效排查
我用C# ASP.NET实现了TextBox1的搜索自动补全功能,用户输入时从SQL数据库获取候选文本显示在控件下方。本地Visual Studio运行完全正常,但上传到Cpanel网站后,补全结果完全不显示,也没有任何错误提示,求帮忙排查问题。
前端代码(Default.aspx)
<link href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> $(document).ready(function () { SearchText(); }); function SearchText() { $("#TextBox1").autocomplete({ source: function (request, response) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Default.aspx/GetName", data: "{'Name':'" + document.getElementById('TextBox1').value + "'}", dataType: "json", success: function (data) { if (data.d.length > 0) { response($.map(data.d, function (item) { return { label: item.split('/')[0], val: item.split('/')[1] } })); } else { response([{ label: 'No Records Found', val: -1 }]); } }, error: function (result) { alert("Error"); } }); }, select: function (event, ui) { if (ui.item.val == -1) { return false; } $('#lblUserId').text(ui.item.val); } }); } </script>
TextBox控件代码
<asp:TextBox ID="TextBox1" Class="searchbox1" placeholder="Search anything" AutoPostBack="false" Font-Size="18px" Height="40px" Width="300px" runat="server"></asp:TextBox>
后端代码(Default.aspx.cs)
[WebMethod] public static List<string> GetName(string Name) { List<string> Result = new List<string>(); using (SqlConnection con = new SqlConnection("Data Source=Myservername;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=myID; password=mypassword")) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "Select Model as Name from AAProduct_Details where Model LIKE '%'+@SearchEmpName+'%'"; cmd.Connection = con; con.Open(); cmd.Parameters.AddWithValue("@SearchEmpName", Name); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Result.Add(dr["Name"].ToString()); } con.Close(); return Result; } } }
排查建议
- 数据库连接验证:确认Cpanel服务器能访问目标数据库,检查连接字符串中的服务器地址、用户名、密码、数据库名是否和生产环境匹配。本地可能用localhost,生产环境需要远程数据库地址,同时要确保数据库防火墙允许Cpanel服务器IP访问。
- AJAX路径修正:部署后网站的虚拟目录可能和本地不同,相对路径
"Default.aspx/GetName"可能失效。改用绝对路径生成:'<%= ResolveUrl("~/Default.aspx/GetName") %>',确保请求能正确找到WebMethod。 - 混合内容问题:如果网站用HTTPS,前端引入的jQuery和jQuery UI是HTTP链接会被浏览器阻止。把资源链接改成HTTPS:
https://code.jquery.com/...。 - WebMethod配置检查:确保
[WebMethod]标记正确,方法为public static。检查web.config是否允许AJAX访问WebMethod,确认.NET Framework版本配置和本地一致。 - SQL查询优化:生产环境数据库数据是否和本地一致?将SQL语句改成参数化通配符写法,避免拼接问题:
cmd.CommandText = "Select Model as Name from AAProduct_Details where Model LIKE @SearchEmpName"; cmd.Parameters.AddWithValue("@SearchEmpName", "%" + Name + "%"); - 浏览器控制台排查:按F12打开开发者工具,查看Console标签的JS报错,Network标签的AJAX请求状态(是否404、500),这是最直接的问题定位方式。
内容的提问来源于stack exchange,提问作者wowfi pax
相关产品推荐
相关产品推荐

