ajax实例
ajax是一種異步的網頁交互手段,遵守同源策略,現各大瀏覽器都支持。
ajax是一種客戶端(瀏覽器端)和服務端通信技術
使用ajax的時候需要先創建ajax實例,除ie5-6,需要使用ActiveXObject(),創建,其他的需要使用XMLHttpRequest()創建,創建ajax實例,需要用到new關鍵字。
XMLHttpReuqest的核心屬性:
xhr.responseText:服務器端相應數據
xhr.responstXML:text/xml
xhr.status: http相應狀態
xhr.statusText: http狀態說明
xhr.readystate:
new xhr()? //0
open()? ?? //1
send() //2
接收相應? //3
相應接受完畢? //4
XMLHttpRequest核心方法:
xhr.open()? //發送請求,get傳null,post傳參數
xhr.send(); //接受響應前執行abort終止xhr后續操作和訪問
xhr.abort();
//reasState狀態變更事件
xhr.onreadystatechange()
對應以上狀態的變化
0.創建xhr ----new XMLHttpRequest() , onreadystatecange
1.初始化請求 ----open()
2.發送請求 ---- send()
3.接受返回數據 ---- readyState ==3
4.接受完畢 ----readyState ==4 onreandystatechange函數內容
代碼示例
//封裝兼容低版本IE瀏覽器的xhr函數。
//ie低版本支持參數:“MSXML.XMLHttp.6.0”,"MSXML.XMLHttp.3.0",“MSXML>XMLHttp”
function createXhr(){
if(typeof XMLHttpRequest != 'undefined'){
return new XMLHTTPRequest();
}else if(typeof ActiveXObject != 'undefined'){
var? tmp = '',
//低版本IE使用ActiveXObject.傳參方式創建xhr對象,主要支持一下參數;
strList ==['MSXML.XMLHttp..0','MSXML.XMLHttp.3.0','MSXML.XMLHttp'];
for (var n in strList){
//異常處理,'try'
中代碼出現異常會執行catch中的代碼,而不會影響到外部后續代碼執行
try{
new ActiveXObject(strList[n]);
var tmp = strList[n];
break;
}catch(e){
console.log(e);
}
}
if(tmp = ''){
console.log('您的瀏覽器目前不支持ajax請求');
}else{
return new ActiveXObject(tmp);
}
}else{
console.log('您的瀏覽器目前不支持ajax請求');
}
}
//封裝公共請求函數
function sendRequest(callback){
var xhr = createXhr();
//綁定readyState監聽事件
xhr.onreadystatechange = function(){
if(xhr.status == '200'? || xhr.status =='304' ){
if(xhr.readyState =='4'){
//JSON.parse();
callback && callback(JSON.parse(xhr.responseText));
}
}?
};
//請求對象初始化
xhr.open("get","ajaxText.json",false);
//發送請求
xhr.send();
}
?
轉載于:https://www.cnblogs.com/browse/p/10143070.html
總結
- 上一篇: 写在2018的总结
- 下一篇: 数独高阶技巧入门之四:简单异数链