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