我想在文本框中输入一个关键字,按回去后在数据库中查询相关内容。请赐教,谢谢!
你好,
首先你需要有一个function 去实现回车功能。回车功能触发后台查询事件。利用Ajax 将文本框的值传到服务器查询,得到的结果再返回给浏览器。如果你对jquery,ajax,数据库查询 不了解,那么先去了解他们的基础知识。
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$("#TextBox1").keypress(function (event) {
if (event.which === 13) {
$.ajax({
type: "POST",
url: "WebForm9.aspx/Test",
data: '{"tb":"' + $("#TextBox1").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "Json",
success: function (data) {
alert(data.d);
}
})
}
})
})
</script>
Webmethod:
[WebMethod]
public static string Test(string tb)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["mydatabase"].ConnectionString);
conn.Open();
string qry = "select num from Test where Id=@tb";
SqlCommand cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("@tb", tb);
SqlDataReader reader = cmd.ExecuteReader();
List<string> ttest = new List<string>();
while (reader.Read())
{
ttest.Add(reader[0].ToString());
}
return JsonConvert.SerializeObject(ttest);
}