原生寫Ajax方法
技術標籤:Javascript
原生Ajax
GET方式
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://127.0.0.1:80/user.php?username=admin&password=123');
xhr.send();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
}
}
POST方式
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://127.0.0.1:80/user.php');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send('username=admin&password=123');
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.responseText);
}
}
封裝成Ajax方法
var Ajax = {
get: function(url,callback){
// XMLHttpRequest物件用於在後臺與伺服器交換資料
var xhr=new XMLHttpRequest( );
xhr.open('GET',url,false);
xhr.onreadystatechange=function(){
// readyState == 4說明請求已完成
if(xhr.readyState==4){
if(xhr.status==200 || xhr.status==304){
console.log(xhr.responseText);
callback(xhr.responseText);
}
}
}
xhr.send();
},
// data應為'a=a1&b=b1'這種字串格式,在jq裡如果data為物件會自動將物件轉成這種字串格式
post: function(url,data,callback){
var xhr=new XMLHttpRequest();
xhr.open('POST',url,false);
// 新增http頭,傳送資訊至伺服器時內容編碼型別
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
if (xhr.readyState==4){
if (xhr.status==200 || xhr.status==304){
// console.log(xhr.responseText);
callback(xhr.responseText);
}
}
}
xhr.send(data);
}
}
程式碼註釋
程式碼註釋:
1.open(method, url, async) 方法需要三個引數:
method:傳送請求所使用的方法(GET或POST);與POST相比,GET更簡單也更快,並且在大部分情況下都能用;然而,在以下情況中,請使用POST請求:
①無法使用快取檔案(更新伺服器上的檔案或資料庫)
②向伺服器傳送大量資料(POST 沒有資料量限制)
③傳送包含未知字元的使用者輸入時,POST 比 GET 更穩定也更可靠
url:規定伺服器端指令碼的 URL(該檔案可以是任何型別的檔案,比如 .txt 和 .xml,或者伺服器指令碼檔案,比如 .asp 和 .php (在傳回響應之前,能夠在伺服器上執行任務));
async:規定應當對請求進行非同步(true)或同步(false)處理;true是在等待伺服器響應時執行其他指令碼,當響應就緒後對響應進行處理;false是等待伺服器響應再執行。
2.send() 方法可將請求送往伺服器。
3.onreadystatechange:存有處理伺服器響應的函式,每當 readyState 改變時,onreadystatechange 函式就會被執行。
4.readyState:存有伺服器響應的狀態資訊。
0: 請求未初始化(代理被建立,但尚未呼叫 open() 方法)
1: 伺服器連線已建立(open方法已經被呼叫)
2: 請求已接收(send方法已經被呼叫,並且頭部和狀態已經可獲得)
3: 請求處理中(下載中,responseText 屬性已經包含部分資料)
4: 請求已完成,且響應已就緒(下載操作已完成)
5.responseText:獲得字串形式的響應資料。
6.setRequestHeader():POST傳資料時,用來新增 HTTP 頭,然後send(data),注意data格式;GET傳送資訊時直接加引數到url上就可以,比如url?username=admin&password=123。
ES6的 Promise
const getJSON = function (url) {
const promise = new Promise(function (resolve, reject) {
const handler = function () {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("promise.json").then(function (json) {
console.log('Data: ', json);
}, function (error) {
console.error('err', error);
});
// 外掛Promise例項物件
new Promise((resolve, reject) => {
if (false) {
resolve("成功的資料"); // 成功的資料 呼叫resolve函式,把資料傳入
} else {
reject("失敗的資料"); // 失敗的資料 呼叫reject函式,把輸入傳入
}
})
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
Ajax的原理
Ajax 的原理簡單來說通過 XmlHttpRequest 物件來向伺服器發非同步請求,從伺服器獲得資料,然後用javascript來操作DOM而更新頁面。這其中最關鍵的一步就是從伺服器獲得請求資料。
要清楚這個過程和原理,我們必須對 XMLHttpRequest 有所瞭解。XMLHttpRequest 是 ajax 的核心機制,它是在 IE5 中首先引入的,是一種支援非同步請求的技術。簡單的說,也就是 javascript 可以及時向伺服器提出請求和處理響應,而不阻塞使用者,達到無重新整理的效果