我需要使用AJAX從數據庫中創建自動完成文本框,我試過這個。從數據庫使用AJAX的JQuery自動完成文本框使用ASP.Net的PageMethods不工作在Internet Explorer中
HTML代碼...
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function() {
$("[id$=txtSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfCustomerId]").val(i.item.val);
},
minLength: 1
});
});
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
C#代碼
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
}
}
conn.Close();
}
}
return customers.ToArray();
}
它工作正常,在瀏覽器,Mozilla但在Internet Explorer 11兼容性模式不工作。是有辦法解決它在IE兼容模式下? 我要糾正在兼容模式下的錯誤.. 在IE瀏覽器的顯示錯誤:
JavaScript runtime error: 'JSON' is undefined
關於 'JSON' 是不確定的ERR或者,確保在所有對象(包括從服務器返回的對象)中的最後一個元素之後沒有逗號,另一件事 - 確保您沒有在兼容模式下運行IE以查看真正的舊版本。 –
@Samuil Petrov我正在兼容模式下運行它..我想糾正它在這種模式下, – Nithin
據我所知,對於某些版本,當「<!DOCTYPE html>」被添加到文檔的開始時,沒有解決你的問題,你可以使用一些跨瀏覽器JSON對象庫,如json2.js:https://github.com/douglascrockford/JSON-js(你只需要包括腳本,它會修復的東西) –