var http = null;
複製代碼
http = new XMLHttpRequest();
複製代碼
open方法有三個參數,分別是javascript
http.open('GET' , '/api/test.php?name=wang' , true);
複製代碼
若是爲POST提交的話,那麼須要設置請求頭部,在把參數設置在sen();中php
http.open('POST','/api/test.php',true)
http.setRequestHeder(xxxxx格式);
http.send('name=wang');
複製代碼
http.send();
複製代碼
提交請求後,咱們能夠經過onreadystatechage去監測響應,看下是否成功,readyState一共有五個狀態,到達4的時候說明相應內容已經解完成了,也能夠經過XMLHttpRequest.onload來代替,當等於4時,經過status獲取狀態碼。java
http.onload = function (){
if(http.status === 200){
console.log('ajax yes!');
}else{
console.log('ajax no!')
}
}
複製代碼
狀態碼 | 信息 |
---|---|
200 | 表示響應結果請求被正常處理了 |
204 | 表示請求資源成功,可是沒有資源能夠返回 |
206 | 表示請求資源的某一部分,響應中包含content-range |
301 | 表示資源的訪問路徑(URL)被變動 |
302 | 表示請求的資源已經在其餘位置了,可是默認你已經知道了 |
303 | 表示請求的資源已經在其餘位置了,應使用 GET 方法定向獲取請求的資源。 |
304 | 表示資源已經請求到到了,可是未能按照正常的方式請求 |
307 | 臨時重定向。 |
400 | 請求報文中存在語法錯誤,須要修改請求內容從新請求 |
401 | 須要經過http認證,若以前已進行過 1 次請求,則表示用 戶認證失敗 |
403 | 服務器拒絕你的的訪問 |
404 | 服務器上沒有請求的資源,多是地址寫錯了....... |
405 | 客戶端的請求方法被服務器禁止 |
500 | 服務器資源發生了錯誤 |
503 | 服務器沒法請求 |
總結 | 2xx爲請求成功,3xx爲URL被改變了,4xx客戶端錯誤,5xx服務器錯誤 |
/** /** * ajax封裝,參數傳遞一個對象 * url : 請求地址 * type : 請求方式 * dataType : 請求值返回值 * data : 參數對象 * async : 異步 * success : function 成功函數 => 參數是響應內容 * error : function 異常函數 => 參數內容是響應碼 **/
var ajax = function (obj) {
//默認傳入一個對象,若是沒有,就爲空對象
obj = obj || {};
//默認GET請求
obj.type = (obj.type || 'GET').toUpperCase();
//默認返回JSON數據
obj.dataType = obj.dataType || 'JSON';
//默認異步請求
obj.async = obj.async || true;
//參數處理,執行getParams方法
var data = getParams(obj.data);
var http;
/** * 建立AJAX的實例適配 * W3C使用XMLHttpRequest * IE使用ActiveXObject('Microsoft.XMLHTTP'); * */
if (window.XMLHttpRequest){
//w3c
http = new XMLHttpRequest();
}else {
//IE
http = new ActiveXObject('Microsoft.XMLHTTP');
}
/** * 請求方式的封裝 * GET和POST請求 * */
if (obj.type === 'GET'){
http.open("GET",obj.url+'?'+data,obj.async);
http.send();
}else if (obj.type === 'POST'){
http.open('POST',obj.url,obj.async);
//設置頭部參數
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//提交post數據
http.send(data);
}
/** * 監聽響應接口 * 若是步驟4的請求狀態碼爲正確的就執行success函數 * 若是錯誤的話就執行error函數 * */
http.onreadystatechange = function () {
if (http.readyState === 4){
//若是響應內容完成了,判斷狀態碼
var status = http.status;
if (status >= 200 && status < 300){
//回調
obj.success && obj.success(http.responseText,http.responseXML);
} else {
obj.error && obj.error(status);
}
}
};
};
/** * 對象參數的處理 * 轉換成爲須要的字符串 */
function getParams(data) {
var arr = [];
for (var param in data){
arr.push(encodeURIComponent(param) + '=' +encodeURIComponent(data[param]));
}
console.log(arr);
arr.push(('randomNumber=' + Math.random()).replace('.'));
return arr.join('&');
}
複製代碼
jQuery封裝的ajax的使用 GETjquery
$.ajax({
type:'get',
url: "url",
data:{'foo':'bar'},
success: function(res) {
load_content(res);
}
});
複製代碼
POSTajax
$.ajax({
url: "url",
success: function(res) {
//設置到頁面上
console.log(typeof res);
}
});
複製代碼
jquery的ajax原理也相對差很少,它給開發者處理了很是多的兼容性問題,大大優化了開發者在寫ajax形成的代碼重複。。。。。。。。。。api