如果要用原生的JS實現(xiàn)Ajax怎么整呢,讓我們一起來整一個試試。
方法:
/**
* 原生js封裝ajax方法
* @param {Object} conf
* ajax({
type:"post",
url:"test.php",
data:"name=xx&pwd=xx",
dataType:"json",
success:function(data){
console.log(data);
}
});
*/
function _ajax(conf){
//創(chuàng)建xhr對象
var createAjax = function() {
var xhr = null;
try {
//IE系列瀏覽器
xhr = new ActiveXObject("microsoft.xmlhttp");
} catch (e1) {
try {
//非IE瀏覽器
xhr = new XMLHttpRequest();
} catch (e2) {
window.alert("您的瀏覽器不支持ajax,請更換岳链!");
}
}
return xhr;
};
// 初始化
//type參數(shù),可選
var type = conf.type;
//url參數(shù),必填
var url = conf.url;
//data參數(shù)可選劲件,只有在post請求時需要
var data = conf.data;
//datatype參數(shù)可選
var dataType = conf.dataType;
//回調(diào)函數(shù)可選
var success = conf.success;
if (type == null){
//type參數(shù)可選掸哑,默認(rèn)為get
type = "get";
}
if (dataType == null){
//dataType參數(shù)可選,默認(rèn)為text
dataType = "text";
}
// 創(chuàng)建ajax引擎對象
var xhr = createAjax();
// 打開
xhr.open(type, url, true);
// 發(fā)送
if (type == "GET" || type == "get") {
xhr.send(null);
} else if (type == "POST" || type == "post") {
xhr.setRequestHeader("content-type",
"application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if(dataType == "text"||dataType=="TEXT") {
if (success != null){
//普通文本
success(xhr.responseText);
}
}else if(dataType=="xml"||dataType=="XML") {
if (success != null){
//接收xml文檔
success(xhr.responseXML);
}
}else if(dataType=="json"||dataType=="JSON") {
if (success != null){
//將json字符串轉(zhuǎn)換為js對象
success(eval("("+xhr.responseText+")"));
}
}
}
};
}
詳細(xì)說明:
1.Ajax步驟:1.創(chuàng)建零远,2.打開連接苗分,發(fā)送數(shù)據(jù),3.接收數(shù)據(jù)
1.1關(guān)于創(chuàng)建:
除了ie低版本牵辣,其它都支持XMLHttpRequest對象
1.2關(guān)于連接:
open(method,url,async)主要有三個參數(shù)摔癣,關(guān)于post和get方法需要注意,get方法參數(shù)是放URL上進行傳輸纬向,post是單獨作為send的參數(shù)傳輸?shù)胶笈_的择浊,因此,如果用post方法我們必須設(shè)置請求頭傳的數(shù)據(jù)類型setRequestHeader('content-type',value),value可以是application/x-www-form-urlencoded,multipart/form-data等逾条。
1.3關(guān)于接收數(shù)據(jù):
當(dāng)readyState變化時會調(diào)用onreadystatechange
readyState主要有五種狀態(tài):
| 值 | 狀態(tài) | 描述 |
| 0 | UNSENT (未打開) | open()方法還未被調(diào)用. |
| 1 | OPENED (未發(fā)送) |
open()方法已經(jīng)被調(diào)用.
|
| 2 | HEADERS_RECEIVED (已獲取響應(yīng)頭) | send()方法已經(jīng)被調(diào)用, 響應(yīng)頭和響應(yīng)狀態(tài)已經(jīng)返回. |
| 3 | LOADING (正在下載響應(yīng)體) | 響應(yīng)體下載中; responseText中已經(jīng)獲取了部分?jǐn)?shù)據(jù). |
| 4 | DONE (請求完成) | 整個請求過程已經(jīng)完畢. |
response
響應(yīng)實體的類型由 responseType 來指定琢岩, 可以是 ArrayBuffer, Blob师脂, Document担孔, JavaScript 對象 (即 "json"), 或者是字符串吃警。如果請求未完成或失敗糕篇,則該值為 null。
responseType
設(shè)置該值能夠改變響應(yīng)類型酌心。就是告訴服務(wù)器你期望的響應(yīng)格式拌消。
| Value | Data type of response property |
| "" (空字符串) | 字符串(默認(rèn)值) |
| "arraybuffer" | ArrayBuffer |
| "blob" | Blob |
| "document" | Document |
| "json" | JavaScript 對象,解析自服務(wù)器傳遞回來的JSON 字符串安券。 |
| "text" | 字符串 |
responseText
此次請求的響應(yīng)為文本墩崩,或是當(dāng)請求未成功或還未發(fā)送時為 null。只讀完疫。
responseXML
本次請求的響應(yīng)是一個 Document 對象泰鸡,如果是以下情況則值為 null:請求未成功,請求未發(fā)送壳鹤,或響應(yīng)無法被解析成 XML 或 HTML盛龄。當(dāng)響應(yīng)為text/xml 流時會被解析。當(dāng) responseType 設(shè)置為"document"芳誓,并且請求為異步的余舶,則響應(yīng)會被當(dāng)做 text/html 流來解析。只讀.
status
該請求的響應(yīng)狀態(tài)碼 (例如, 狀態(tài)碼200 表示一個成功的請求).只讀.
1開頭的是information responses
2開頭是響應(yīng)成功
3重定向信息
4客戶端錯誤信息
5服務(wù)器端響應(yīng)錯誤
statusText
該請求的響應(yīng)狀態(tài)信息,包含一個狀態(tài)碼和原因短語 (例如 "200 OK"). 只讀.
upload
可以在 upload 上添加一個事件監(jiān)聽來跟蹤上傳過程锹淌。
不考慮瀏覽器兼容性匿值,當(dāng)時在一個項目中,我發(fā)現(xiàn)在谷歌瀏覽器下赂摆,上傳文件的時候挟憔,在谷歌瀏覽器的狀態(tài)欄可以看到上傳進度钟些,我想谷歌應(yīng)該有提供方法出來供開發(fā)調(diào)用,開啟調(diào)試發(fā)現(xiàn)確實有绊谭。
代碼如下:
進度條當(dāng)時是easyui的政恍。
xhr.onloadstart = $.message.progress({text:'{value}%',title:'文件上傳',interval:false});
xhr.upload.onprogress = function(evt){
if(evt.lengthComputable){
var comVal = Math.round(evt.loaded * 100 / evt.total);
$("div.messager-p-bar").progressbar("setValue", comVal);
}
}
補充:
post和get主要差別
發(fā)送數(shù)據(jù)的方式:get是放URL上,post是單獨作為請求體
安全性达传,post比get相對安全篙耗,因為get在URL上可見的
大小,get有限制宪赶,一般幾kb宗弯,post受服務(wù)器端限制,一般可以幾十兆