什么是AJAX?
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)贤牛。 AJAX 是一種用于創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁(yè)的技術(shù)。 通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換则酝,AJAX 可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新殉簸。這意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新沽讹。 傳統(tǒng)的網(wǎng)頁(yè)(不使用 AJAX)如果需要更新內(nèi)容般卑,必需重載整個(gè)網(wǎng)頁(yè)面。 有很多使用 AJAX 的應(yīng)用程序案例:百度智能提示爽雄,天氣預(yù)報(bào)蝠检。
AJAX的實(shí)現(xiàn)?
var xhr = null ; //創(chuàng)建ajax對(duì)象
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new Activexobject('Mircrsoft.XMLHTTP');
}
xhr.open('get', url,true);// 配置發(fā)生請(qǐng)求
xhr.send(null); //執(zhí)行發(fā)生請(qǐng)求
//指定回調(diào)函數(shù)
xhr.onreadystatechange =function(){
if (xhr.readyState == 4&&xhr.status == 200) {
var data = xhr.responseText;
}
}
簡(jiǎn)單的封裝ajax挚瘟?
function ajax(data){
//data={data:"",dataType:"xml/json",type:"get/post "叹谁,url:"",asyn:"true/false",success:function(){}, failure:function(){}}
//data:{username:123,password:456}
//data = 'username=123&password=456';
//第一步:創(chuàng)建xhr對(duì)象
var xhr = null;
if(window.XMLHttpRequest){//標(biāo)準(zhǔn)的瀏覽器
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//第二步:準(zhǔn)備發(fā)送前的一些配置參數(shù)
var type = data.type == 'get'?'get':'post';
var url = '';
if(data.url){
url = data.url;
if(type == 'get'){
url += "?" + data.data + "&_t="+new Date().getTime();
}
}
var flag = data.asyn == 'true'?'true':'false';
xhr.open(type,url,flag);
//第三步:執(zhí)行發(fā)送的動(dòng)作
if(type == 'get'){
xhr.send(null);
}else if(type == 'post'){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(data.data);
}
//第四步:指定回調(diào)函數(shù)
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(typeof data.success == 'function'){
var d = data.dataType == 'xml'?xhr.responseXML:xhr.responseText;
data.success(d);
}
}else{
if(typeof data.failure == 'function'){
data.failure();
}
}
}
}
}