現在ajax的應用相當廣泛了,最簡單的有微軟的asp.net ajax、jquerry等等,使用這些第三方無法瞭解ajax的原理。
想瞭解ajax的實現方法,必須自已動手寫,下面是個人的總結:
1.前台頁面代碼list.html:
Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<script language="javascript" type="text/javascript">
CreateXmlHttp = function()
{
var xmlhttp;
try{
xmlhttp=new ActiveXObject('Msxml2.XMLHTTP');
}catch(e){
try{
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}catch(e){
try{
xmlhttp=new XMLHttpRequest();
}catch(e){}
}
}
// alert(xmlhttp);
return xmlhttp;
}
GetXmlData = function(uri,json)
{
var xmlhttp=CreateXmlHttp();
var base=this;
//定義XMlHttpRequest對象的事件處理常式
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
base.xmlhttp = xmlhttp;
if(xmlhttp.status==200)
{
base.onsuccess();
}
else
{
base.onfailure();
}
}
}
//建立一個串連
xmlhttp.open("post",uri,true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//發送請求
xmlhttp.send(json);
this.onsuccess=function(){};
this.onfailure=function(){};
}
GetUserValue = function()
{
var ObjGetData=new GetXmlData("ajax.aspx",null);
ObjGetData.onsuccess=function()
{
$("user1").innerHTML = this.xmlhttp.responseText;
$("message2").innerHTML = $("Select1").options[$("Select1").selectedIndex].value
}
}
$ = function(obj)
{
return document.getElementById(obj);
}
</script>
<a href="javascript:GetUserValue();">aa</a>
<input type="hidden" id="username" value="antyi" /><br />
<div id="user1">message</div>
<div id="message2">message2</div>
<select multiple id="Select1">
<option value="antyi">antyi</option>
<option value="gdou">gdou</option>
<option value="longtek">longtek</option>
</select>
</BODY>
</HTML>
添加ajax.aspx頁面,在ajax.aspx.cs頁面的Page_Load方法修改為:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("hello ajax!");
}
瀏覽,點擊aa連結,即可看到效果(此代碼已在IE和Opera瀏覽器測試通過)。