Ajax:同步:請(qǐng)求后不可以做其他的事
異步:請(qǐng)求后還可以做其他的事;
局部刷新的原理:1.創(chuàng)建異步對(duì)象 2.異步讀取數(shù)據(jù) 3.根據(jù)異步狀態(tài)獲取最終數(shù)據(jù) 4.獲取并顯示異步返回的數(shù)據(jù)
1.創(chuàng)建異步調(diào)用對(duì)象
Var xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
2.異步讀取數(shù)據(jù)
xmlhttp.open(Method,URL,Aysc);
Method:表示向服務(wù)器發(fā)送請(qǐng)求的發(fā)法(get,post,head,put,delete),
get將參數(shù)追加到URL中發(fā)送,post將參數(shù)串放在請(qǐng)求中發(fā)送。
URL:請(qǐng)求服務(wù)器的地址
Aysc:是否使用異步方法(true/false);
發(fā)送請(qǐng)求的方法Send
xmlhttp.send()或xmlhttp.send(“參數(shù)”);
Xmlhttp.open(“get”,”http://www.baidu.com/?id=yang”,true);
Xmlhttp.send();
或
Xmlhttp.open(“post”,”http://www.baidu.com”,true);
Xmlhttp.send(“id=yang”);
3 根據(jù)異步狀態(tài)獲取最終數(shù)據(jù)
xmlhttp.readystate==4 && xmlhttp.status==200
Readystate表示交互的狀態(tài)
0: 異步對(duì)象創(chuàng)建完畢未使用open方法
1: 未使用send方法發(fā)送請(qǐng)求
2: send方法完成,等待服務(wù)求響應(yīng)
3: 正在接受數(shù)據(jù),但未完成
4: 調(diào)用完成,可以獲取返回的數(shù)據(jù)
4 獲取并顯示異步返回的數(shù)據(jù)
//調(diào)用完成后可以用responseText或responseXml獲取數(shù)據(jù)(實(shí)現(xiàn)局部刷新)
Document.getElementById(“對(duì)象”).innerText=xmlhttp.responseText ;
function sendData()//用Jquery來處理Ajax
{
//Jquery的get方法
$.get("AjaxDemos.aspx?type=ajax",function(data){
$("#dateNow").text(data);
});
//Jquery的post方法 注:post回發(fā)數(shù)據(jù)要用Form表單來進(jìn)行獲取
$.post("Ajax1.ashx","type=ajax&id=13",function(text){
$("#dateNow").text(text);
}) ; //注 .ashx文件為一般處理程序文件
//用總體的ajax
$.ajax({
url:"Ajax1.ashx",
type:"post",
dataType:"text",
data:"type=我的愛好&id=興趣",//支持中文
success:function(msg){
$("#dateNow").text(msg);
},
error:function(){
$("#dateNow").text("Ajax請(qǐng)求失敗!");
}
});
}
//body內(nèi)部
<div>
<ul>
<li id='dateNow' > </li>
</ul>
</div>
<a href="#" onclick="sendData()" >發(fā)送Ajax請(qǐng)求</a>
Page_Load()內(nèi)
try
{
string temp = Request.QueryString["type"].ToString();//get方法獲取
Response.Clear();
Response.Write(DateTime.Now);
Response.End();
Response.StatusCode = 200;
Response.Flush();
}
catch
{
}
//.ashx(一般處理程序)內(nèi)ProcessRequest()方法相當(dāng)于Page_Load()方法
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string type= context.Request.Form["type"].ToString();//post方式獲取
string id = context.Request.Form["id"].ToString();
context.Response.Write("Hello World,"+id+",Type:"+type);
context.Response.StatusCode = 200;
context.Response.Flush();
}
//Jquery中g(shù)et,post方法如何使用:
1.get方法使用
jQuery.get(url, [data], [callback], [type])
url(必選) 待載入頁面的URL地址
data (可選) 待發(fā)送 Key/value 參數(shù)。例如:"type=我的愛好&id=興趣";
callback (可選) Function 載入成功時(shí)回調(diào)函數(shù)。
type (可選) 返回內(nèi)容格式,xml, html, script, json, text, _default。
2.post方法使用
jQuery.post(url, [data], [callback], [type])
同上:不過data的獲得與get不同要用到Form表單來獲得