Tables | Are | Cool |
---|---|---|
col 3 is | right-aligned | $1600 |
col 2 is | centered | $12 |
zebra stripes | are neat | $1 |
1 (21).jpg
AJAX介紹
今天學(xué)習(xí)了一下ajax特此記錄一下灌诅,先放兩參考鏈接
- https://blog.csdn.net/weixin_39194176/article/details/80933777
- https://blog.csdn.net/c__dreamer/article/details/80456565
- Ajax 不是一種新的編程語言糠悯,而是一種用于創(chuàng)建更好更快以及交互性更強(qiáng)的Web應(yīng)用程序的技術(shù)趣些。
- Ajax 通過在后臺與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,Ajax可以使網(wǎng)頁實(shí)現(xiàn)異步更新剧浸。這意味著可以在不重新加載整個網(wǎng)頁的情況下画机,對網(wǎng)頁的某部分進(jìn)行更新焊刹。
- 傳統(tǒng)的網(wǎng)頁(不使用 Ajax)如果需要更新內(nèi)容系任,必需重載整個網(wǎng)頁面。
ajax的實(shí)現(xiàn)步驟
- 創(chuàng)建
XMLHTTPRequest
對象(異步調(diào)用對象) - 創(chuàng)建一個新的
HTTP
請求虐块,并指定該HTTP
請求的方法俩滥、URL
及驗(yàn)證信息 - 設(shè)置相應(yīng)
HTTP
請求狀態(tài)變化的函數(shù) - 發(fā)送
HTTP
請求. - 獲取異步調(diào)用返回的數(shù)據(jù).
- 使用JavaScript和DOM實(shí)現(xiàn)局部刷新.
創(chuàng)建XMLHttpRequest對象
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest;
}else{
// 在IE5、IE6之前使用的是 ActiveXObject
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
向服務(wù)器發(fā)送請求
xmlHttp.open('get', 'deom_get.json', 'true');
xmlHttp.send();
- 連接服務(wù)器
- 上面創(chuàng)建的ajax對象xhr贺奠,使用xhr.open("請求方式(GET/POST)"霜旧,url路徑,“異步/同步”)儡率。
- 第三個參數(shù):true===》異步挂据、false===》同步。
- 當(dāng)請求方式為POST的時候儿普,代碼寫法如上崎逃;
- 當(dāng)請求方式為GET的時候,使用xhr.open("請求方式(GET/POST)"眉孩,url路徑 + “个绍?”請求數(shù)據(jù) + ,“異步/同步”)浪汪。
- 發(fā)送請求
- 使用xhr.send()發(fā)送請求
- 當(dāng)請求方式為GET的時候巴柿,發(fā)送請求為xhr.send(null).
- 當(dāng)請求方式為POST的時候,發(fā)送請求為xhr.send(請求數(shù)據(jù))死遭。
- 此外使用POST的時候必須在xhr.send(請求數(shù)據(jù))上面添加
xmlHttp.open('post', 'deom_get.json', 'true');
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send('username=ayf&pwd=123456');
響應(yīng)處理
使用ajax會使用一個事件readystatechange事件:當(dāng)請求被發(fā)送到服務(wù)器時篮洁,我們需要執(zhí)行一些基于響應(yīng)的操作。
- 當(dāng)readystate改變的時候殃姓,就會觸發(fā)這個事件執(zhí)行。
- readyState:請求的狀態(tài)瓦阐,返回的是狀態(tài)碼(0 - 4):0(未初始化)open還沒有調(diào)用蜗侈、1(載入)已經(jīng)調(diào)用了send()正在發(fā)送請求、2(載入完成)send方法已經(jīng)完成 已經(jīng)收到了全部的響應(yīng)內(nèi)容睡蟋、3(解析)正在解析響應(yīng)內(nèi)容踏幻、4(完成)響應(yīng)內(nèi)容解析完成 可以在客戶端用了。
- status:返回請求的結(jié)果碼:返回200(成功)戳杀、返回404(未找到)该面、返回5**(5開頭)(服務(wù)器錯誤)
- responseText 獲得字符串形式的響應(yīng)數(shù)據(jù)夭苗。
- responseXML 獲得XML 形式的響應(yīng)數(shù)據(jù)。
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//請求成功后的操作 這里只打印獲取到的數(shù)據(jù)
console.log(JSON.parse(xmlHttp.responseText));
} else if (xmlHttp.status == 404) {
console.log('找不到頁面');
}
}
一個簡單的Ajax
// 原生js實(shí)現(xiàn) ajax
function ajax() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest;
} else {
// 在IE5隔缀、IE6之前使用的是 ActiveXObject
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// get請求 demo_get.json 中隨便寫一點(diǎn)json數(shù)據(jù) true表示異步請求
xmlHttp.open('get', 'demo_get.json', 'true');
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//請求成功后的操作 這里只打印獲取到的數(shù)據(jù)
console.log(JSON.parse(xmlHttp.responseText));
} else if (xmlHttp.status == 404) {
console.log('找不到頁面');
}
}
}
Ajax封裝 有點(diǎn)jq中ajax的感覺了
function ajax(obj) {
if (Object.prototype.toString.call(obj) != '[object Object]') {
console.log('錯誤使用');
}
// 可以默認(rèn)部分參數(shù)
obj.type = obj.type || 'get';
obj.async = obj.async || 'true';
// 獲取data中的數(shù)據(jù) 這里data必須是一個{};
if (obj.data && Object.prototype.toString.call(obj) == '[object Object]') {
var param = '';
/*下面注釋是我一開始能想到的方法*/
// for (const key in obj.data) {
// if (obj.data.hasOwnProperty(key)) {
// param += `${key}=${obj.data[key]}&`;
// }
// }
// 去掉最后兩個 &
// param = param.slice(0, param.length - 2);
/*這是鏈接中'別人家的代碼' 別人家的就是優(yōu)秀*/
param = formsParams(obj.data);
function formsParams(data) {
var arr = [];
for (var prop in data) {
arr.push(prop + "=" + data[prop]);
}
/*
join 是Array原型上面的方法题造;
join() 方法將一個數(shù)組(或一個類數(shù)組對象)的所有元素連接成一個字符串并返回這個字符串。
如果數(shù)組只有一個項(xiàng)目猾瘸,那么將返回該項(xiàng)目而不使用分隔符界赔。
*/
return arr.join("&");
}
var xmlHttp;
xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
// 不區(qū)分大小寫
var ignoreCaseGet = /get/i;
var ignoreCasePost = /post/i;
if (ignoreCaseGet.test(obj.type)) { //get 請求方式
obj.url = obj.url + `?${param}`;
xmlHttp.open(obj.type, obj.url, obj.async);
xmlHttp.send();
} else if (ignoreCasePost.test(obj.type)) { //post請求方式
xmlHttp.open(obj.type, obj.url, obj.async);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(param);
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
obj.success(xmlHttp.responseText);
} else {
obj.error();//這個有點(diǎn)假的 以后再搞
}
}
}
}
var obj = {
url: 'demo_get.json',
data: {
username: 'ayf',
pwd: '123456'
},
success: function(res) {
console.log(res);
},
error: function() {
console.log('網(wǎng)絡(luò)錯誤');
}
}
ajax(obj)