一、get方式
get方式是最為常見的,一般實現用戶登錄,修改密碼用的都是get方式
1,新建一html文檔,body標簽內容如下
<body style="text-align: center">
<input type ="text" id ="txt" />
<br />
<input type ="button" value ="get方式回調" onclick ="get()" />
</body>
2,js代碼文件
var xhr=getXHR();//獲得xmlhttprequest對象,getXHR函數的具體實現這里不給出,因為非常簡單
function get()
{
var str=document.getElementById ("txt").value;
var url="PageAjax.aspx?argument="+escape(str);//編碼str
xhr.open("get",url,true);
xhr.onreadystatechange=renew;
xhr.send(null);//不發送任何內容,因為url中包含了參數數據
}
function renew()
{
if (xhr.readystate==4)
{
if (xhr.status==200)
{
var response=xhr.responsetext;
var res=response.split('');
alert(res[0]);
}
}
}
3,服務器端PageAjax.aspx.cs文件代碼如下
protected void Page_Load(object sender, EventArgs e)
{
if (Request["argument"] != null)
{
string res ="成功實現post方式回調!傳入的參數是:"+ Request["argument"].ToString()+"";
Response.Write(res);
}
}
4,到此一個簡單的get方式回調完成。
二、post方式
由于get方式每次都要傳入參數到url地址上,像用戶名,密碼之類的參數由于字符比較少,完全可以考慮這中傳遞方式,但是當有很多參數、并且參數的字符串值很長時(比如博客,你不可能把整篇博客的內容都以參數的方式傳遞到url上),這種方式就不好了,由于有了post方式的出現。
1,新建一html文檔,body標簽內容如下
<textarea id="TextArea1" style="width: 323px; height: 76px"></textarea>
<br />
<input id="Button1" type="button" value="post方式回調" onclick="post()" />
2,js代碼文件
var xhr=getXHR();//獲得xmlhttprequest對象,getXHR函數的具體實現這里不給出,因為非常簡單
function post()
{
var str=document.getElementById ("TextArea1").value;
var poststr="arg="+str;
var url="PageAjax.aspx?time="+new Date();//加一時間戳,放置發回的數據是服務器緩存的數據
xhr.open("post",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //告訴服務器發送的是文本
//xhr.setRequestHeader("Content-Type", "text/xml"); //告訴服務器發送的是一個xml文件
xhr.onreadystatechange=update;
xhr.send(poststr);//發送poststr數據到服務器
}
function update()
{
if (xhr.readystate==4)
{
if (xhr.status==200)
{
var response=xhr.responsetext;
var res=response.split('');
alert(res[0]);
}
}
}
3,服務器端PageAjax.aspx.cs文件代碼如下
protected void Page_Load(object sender, EventArgs e)
{
if (Request["arg"] != null)
{
string res = "成功實現get方式回調!傳入的參數是:" + Request["arg"].ToString() + "";
Response.Write(res);
}
}
4,到此一個簡單的post方式回調完成。