今天封裝了一個(gè)簡單的ajax。所以順便總結(jié)一下。
#######ajax概念
- ajax:Asynchronous JavaScript and XML。異步的JavaScript和XML
- 作用:實(shí)現(xiàn)網(wǎng)頁的異步加載,局部刷新網(wǎng)頁。當(dāng)在向服務(wù)器獲取新數(shù)據(jù)時(shí)不需要刷新整個(gè)網(wǎng)頁,提高用戶體驗(yàn)。
- 優(yōu)點(diǎn):
(1)更新數(shù)據(jù)而不需要刷新頁面: 它能在不刷新整個(gè)頁面的前提下與服務(wù)器通信維護(hù)數(shù)據(jù),由于ajax是按照需求請求數(shù)據(jù),避免發(fā)送那些沒有改變的數(shù)據(jù)
(2)異步通信: 它與服務(wù)器使用異步的方式通信,不會(huì)打斷用戶的操作(卡死頁面)
(3)前后端負(fù)載平衡: 可以將后端服務(wù)器的一些工作轉(zhuǎn)移給客戶端,利用客戶端限制的能力來處理,減輕了服務(wù)器的負(fù)擔(dān)
(4)數(shù)據(jù)與呈現(xiàn)分離: 利于分工,降低前后耦合 - 缺點(diǎn)
(1)瀏覽器歷史記錄的遺失: 在使用AJAX對頁面進(jìn)行改變后,由于并沒有刷新頁面,沒有改變頁面的訪問歷史,當(dāng)用戶想要回到上一個(gè)狀態(tài)時(shí),無法使用瀏覽器提供的后退
(2)AJAX的安全問題: AJAX的出現(xiàn)就像建立起了一直通服務(wù)器的另一條通道,容易遭受到一些攻擊
ajax封裝
可以滿足基本的需求。后面根據(jù)使用情況會(huì)一點(diǎn)點(diǎn)更新。
function ajax(opts){
var xhr = new XMLHttpRequest();
var data = '';
for(var key in opts.data){
data += key + "=" + opts.data[key] + "&";
}
data = data.substring(0,data.length-1);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var result = JSON.parse(xhr.responseText);
opts.success(result);
}else{
opts.error();
}
}
}
if(opts.type == "get"){
xhr.open("get",opts.url+"?"+data,true);
xhr.send();
}
if(opts.type == "post"){
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.open("post",opts.url,true);
xhr.send(data);
}
}
調(diào)用格式
ajax({
url: '/login', //接口地址
type: 'get', // 類型, post 或者 get,
data: {
username: 'xiaoming',
password: 'abcd1234'
},
success: function(ret){
console.log(ret); // {status: 0}
},
error: function(){
console.log('出錯(cuò)了')
}
})