XMLHttpRequest 的基本实例Ajax的应用
// JScript 文件
//声明XMLHttpRequest对象
var xmlHttp;
//检验用户信息
function CheckName(userName)
{
createXMLHTTP();//创建XMLHttpRequest对象
var url="checkPage.aspx?Name="+userName;
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange=checkUserName;
xmlHttp.send(null);
}
function createXMLHTTP()
{
if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();//mozilla浏览器
}
else if(window.ActiveXObject)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");//IE老版本
}
catch(e){}
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");//IE新版本
}
catch(e){}
if(!xmlHttp)
{
window.alert("不能创建XMLHttpRequest对象实例!");
return false;
}
}
}
//执行。。。回调函数
function checkUserName()
{
if(xmlHttp.readyState==4)//判断对象状态
{
if(xmlHttp.status==200)//信息成功返回,开始处理信息
{
if(xmlHttp.responseText=="true")
{
document.getElementById("imgName").src="true.gif";
// document.getElementById("divName").innerHTML="成功!";
}
else
{
document.getElementById("imgName").src="false.gif";
// document.getElementById("divName").innerHTML="失败!";
}
}
}
}
-------------------
checkPage.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _checkPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string res = Request.QueryString["Name"].ToString();
if (res == "chc")
{
Response.Write("true");
Response.End();
}
else
{
Response.Write("false");
Response.End();
}
}
}
-----------------------------
default.aspx
<form id="form1" runat="server">
<div>
<script language="javascript" src="checkName.js" type="text/javascript"></script>
<input type="text" id="txtName" onkeyup="CheckName(document.getElementById('txtName').value)" />
<input type="image" id="imgName" />
<div id="divName"></div>
</div>
</form>