都是簡單的實例,所以直接發代碼
靜態頁面Ajax.html
復制代碼 代碼如下:
<html>
<head>
<title>Ajax</title>
<script type="text/javascript">
function loadXMLDoc() {
if (document.getElementById("account").value == "") {
document.getElementById("accDiv").innerHTML = "用戶名不能為空";
return;
}
var xmlHttp;
if(window.XMLHttpRequest) { // code for IE7+
xmlHttp = new XMLHttpRequest();
}
else { // code for IE5/IE6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
if (xmlHttp.responseText == "true") {
document.getElementById("accDiv").innerHTML = "用戶名不可用";
}
else {
document.getElementById("accDiv").innerHTML = "用戶名可用";
}
}
}
var a = document.getElementById("account").value;
// get
xmlHttp.open("GET", "validate.aspx?account=" + a + "&random=" + Math.random, true);
xmlHttp.send();
}
function delData() {
document.getElementById("account").value = "";
document.getElementById("accDiv").innerHTML = "";
}
</script>
</head>
<body>
<h3>ajax</h3>
<table>
<tr>
<td>賬號:</td><td><input id="account" type="text" onblur="loadXMLDoc();" onfocus="delData();"/></td><td><div id="accDiv"></div></td>
</tr>
<tr>
<td>密碼:</td><td><input id="passwd" type="password" /></td>
</tr>
<tr>
<td>確認密碼:</td><td><input id="vPasswd" type="password" /></td>
</tr>
<tr>
<td>姓名:</td><td><input id="name" type="text" /></td>
</tr>
</table>
</body>
</html>
在賬號輸入框失去焦點時調用函數
訪問服務器使用的是Get方法,所以在參數處使用了附加隨機碼來避免緩存。
驗證頁面validate.aspx後台代碼:
復制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.Sql;
using System.Data.SqlClient;
public partial class Ajax_validate_validate : System.Web.UI.Page
{
public SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
if (Exists(Request.QueryString["account"]))
Response.Write("true");
else
Response.Write("false");
Response.End();
}
/// <summary>
/// 獲取數據庫連接
/// </summary>
/// <returns></returns>
protected SqlConnection GetConnection()
{
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new SqlConnection(str);
return conn;
}
protected bool Exists(string account)
{
using (GetConnection())
{
try
{
conn.Open();
string sqlStr = "select count(*) from userinfo where account='" + account + "'";
SqlCommand cmd = new SqlCommand(sqlStr, conn);
int row = Convert.ToInt32(cmd.ExecuteScalar());
if (row > 0)
return true;
else
return false;
}
catch (Exception e)
{
throw e;
}
finally
{
conn.Close();
}
}
}
}
在後台中驗證用戶名是否已經存在於數據庫中,返回真或者假
運行結果:
數據庫很簡單,只建了一張表userinfo,有3個字段:account、passwd、name
注意:在後台往請求頁面寫數據時,當寫完要發送的數據之後,需要調用Response.end()方法來終止寫入,否則可能會發送一個完整頁面過去。