在項目中,經常需要封裝函數,而封裝AJAX是很好的選擇,可以通過傳遞參數動態進行異步交互,而且可以動態轉判斷並且轉換JSON字符串
下面上步驟:
第一步,寫出創建XMLHttpRequest異步對象的方法:
function createXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
然後現在頁面中寫出AJAX異步交互的流程雛形:
<script type="text/javascript" src="createXhr.js"></script>
<body>
<script type="text/javascript">
function ajax(){
var xhr = createXhr();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
//如果想用post提交,添加消息頭xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//使用get提交
xhr.open("get",url,true);
//post
//send(定義需要傳字符串);
xhr.send(null);
}
</script>
</body>
下面進行封裝 -要求實現:可以動態選擇post或者get提交方式,而且可以判斷傳回來的是否是JSON字符串,並且可以定義想要傳的數據
<script type="text/javascript">
function ajax({type,url,data,dataType}){
return new Promise(open=>{
var xhr = createXhr();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
if(dataType =="json")
open(JSON.parse(xhr.responseText));
else
open(xhr.responseText)
}
}
if(type == "get")
url = "?"+data;
xhr.open(type,url,true);
xhr.send(null);
else if(type == "post")
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencode");
xhr.open(type,url,true);
xhr.send(data);
})
}
</script>
這樣封裝完成
原理:
在函數中傳入:type(用來傳入選擇post/get),url(傳入要進行異步的文件路徑),data(要進行傳輸的數據),
dataType(輸入返回類型是不是json)
使用 return new Promise(open=>{})包裹函數,防止回調地獄的產生
判斷返回的數據是否是json字符串 格式,如果是就進行轉換
判斷傳入的請求方式是否是post/get並根據方式的不同進行不同的異步
再調用的時候:
(()=>{
ajax({
type:"xxx",
url:"xxx",
data:"xxx",
dataType:"xxx"
}).then(函數名=>{
函數體
});
})()
這裏使用了匿名函數自調,由於函數在創建的時候,使用了參數解構,故在調用的時候,這幾個參數可以有也可以沒有,
他們是不會影響順序的,由於使用了防止回調地獄產生的return new Promise(open=>{})
故調用的時候,需要在參數結尾加.then(函數名=>{
函數體
})
案例使用:
假設有一個index頁面,需要爲其添加header.html和footer.html
第一步:在index中加入header,設置id爲header,加入footer,設置其id爲footer
第二步:在js中新建header.js和footer.js並調用動態異步獲取
(1)header.js:
(()=>{
var link = document.createElement("link");
link.setAttribute("rel","stylesheet");
link.setAttribute("href","css/header.css");
document.head.appendChild(link);
ajax({
type:"get",
url:"header.html"
}).then(header=>{
document.getElementById("header").innerHTML=html;
});
})()
原理:
先創建link並設置rel和href,並將link加入到index.html的head中 ->讀取header.css樣式
在從header.html中通過異步獲取HTML中的內容並將header中的內容更改爲異步請求回來的數據
第三步:
在index.html底部引入ajax.js與header.js
頁腳步驟同header