前言
每次在做項目的時候,在ajax這塊,都是用的jqury框架本身封裝的$.ajax,$.get,$.post等方法進行異步請求,但是還是想知道他到底是怎麼進行異步請求的封裝,於是自己動手封裝了個最簡單的get,post請求。
GET請求
首先我們需要創建一個 XMLHttpRequest對象,XMLHttpRequest 對象提供了對 HTTP 協議的完全的訪問,包括做出 POST 和 HEAD 請求以及普通的 GET 請求的能力等。
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
ActiveXObject() 用於支持IE5,6瀏覽器
構造好了XMLHttpRequest請求後就可以構造請求以及發送請求
xhr.open('GET',url,true);//構造請求,url爲請求的網址,true爲是否進行異步請求
xhr.send();//發送請求
之後我們需要設置一個監聽器來接受返回的數據
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 && xhr.status == 200 ){
alert(xhr.responseText);//xhr.responseText爲請求所返回的內容
}
};
這裏通過監聽返回碼的變化來確定請求是否成功以及處理返回的數據
之後只需要進行簡單的封裝之後,一個簡單的ajax get請求就完成了,完整代碼如下。
function get(url,callback){
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function checkTimeout(){
if(xhr.readyState !== 4){
aborted = true;
xhr.abort();//關閉請求
}
}
setTimeout(checkTimeout,5*1000);//設置超時時間
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 && xhr.status == 200 ){
callback(xhr.responseText); 執行監聽器方法
}
};
xhr.open('GET',url,true);
xhr.send();
}
調用它其實很簡單,需要設置一個方法監聽器
get('http://localhost:8087/rxd/pre/user/login',function(data){
//執行你的操作
});
POST請求
post請求和get請求差不多,區別主要的就是POST請求需要在發送的時候傳遞參數
xhr.send(params);
完整代碼如下:
function post(url,params,callback){
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function checkTimeout(){
if(xhr.readyState !== 4){
aborted = true;
xhr.abort();
}
}
setTimeout(checkTimeout,5*1000);
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 && xhr.status == 200 ){
callback(xhr.responseText);
}
};
xhr.open('POST',url,true);
xhr.send(params);
}
調用方法:
post('http://localhost:8087/rxd/pre/user/login',{username:'asd',password:'asd'},function(data){
alert(data);
})
總結
以上即是最簡單的ajax的get和post封裝,還有許許多多的地方沒有處理,沒有涉及,但是我們至少知道了平時我們是用的$.ajax,$.get,$.post是如何進行基本的網絡請求的,以及自己也可以寫出一個簡單的ajax的gei,post請求。