利用AJAX驗證輸入的使用者名稱在sqlserver資料庫中是否已經存在
阿新 • • 發佈:2018-11-13
HtmlPage.html:
<html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> var xmlHttp; function Validation() { if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } var name = document.getElementById("Text1"); xmlHttp.open("Get", "Default2.aspx?name=" + name.value); xmlHttp.onreadystatechange= onmessageBack; xmlHttp.send(null); } function onmessageBack(){ if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("result").innerHTML = xmlHttp.responseText; } } </script> </head> <body> <form id="form1" runat="server"> 請在下面的文字框中輸入使用者名稱,進行檢驗<br /> 使用者名稱: <input id="Text1" type="text" onblur="Validation()" /><br /> <div id="result"></div> </form> </body> </html>
Default2.aspx.cs:
private string myConnStr = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { Response.Expires = -1; string name = this.Request.QueryString["name"]; string mydr; SqlConnection myConn = new SqlConnection(myConnStr); string sql = "SELECT UserName from Users WHERE UserName="; sql = sql + "'" + name + "'"; SqlCommand sqlCommand = new SqlCommand(sql, myConn); try { myConn.Open(); if (name != "") { if (sqlCommand.ExecuteScalar() != null) { mydr = sqlCommand.ExecuteScalar().ToString(); Response.Write("該使用者名稱已被註冊,請返回重新註冊!"); Response.End(); } else { Response.Write("該使用者名稱可用。"); Response.End(); } } else { Response.Write("請輸入使用者名稱!"); Response.End(); } } catch (SqlException se) { Response.Write(se.Message + "<br>"); Response.End(); } finally { myConn.Close(); } }
Web.config:
<connectionStrings>
<add name="SQL" connectionString="data source=DESKTOP-NA2OPPJ\SQLEXPRESS;database=users;user id=sa;pwd=123"/>
</connectionStrings>