js腳本發(fā)起HTTP請求必須通過XMLHttpRequest對象物臂,也是通過AJAX進(jìn)行瀏覽器與服務(wù)器通信的接口,不局限于XML产上,可以發(fā)送任何格式的數(shù)據(jù)
XMLHttpRequest本身是JS引擎內(nèi)置的構(gòu)造函數(shù)鹦聪,所有XMLHttpRequest都需要被實(shí)例化 new XMLHttpRequest();
IE5,6使用ActiveX對象: new ActiveXObject('MicrosoftXMLHTTP')
參數(shù)說明
var xhr = new window.HMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
// console.log(xhr.readyState) // 0:請求未初始化
// xhr.open('GET', 'http://...?name=tome&password=123', true);
// xhr.send();
xhr.open('POST', 'http://...', true);
xhr.setReqeustHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('name=tom&password=123');
// console.log(xhr.readyState) // 1:服務(wù)器連接已建立
xhr.onreadystatechange = function(){
// console.log(xhr.readyState) // 2 3 4
if(xhr.readyState === 4 && xhr.status === 200){
console.log(JSON.parse(xhr.responseText));
}
}
open方法(發(fā)送設(shè)置)
xhr.open(method: 請求方式, url: 請求發(fā)送的地址, true異步 / false同步 )
xhr.send(發(fā)送請求)發(fā)送post請求體數(shù)據(jù)用,GET不填寫
xhr.onreadystatechange事件: 掛載到XMLHttpRequest對象上的事件
xhr.readyState屬性: 通過XMLHttpRequest對象發(fā)送HTTP請求的各階段狀態(tài)碼
0:請求未初始化
1:服務(wù)器連接已建立
2:請求已接收
3:請求處理中
4:請求已完成蒂秘,且響應(yīng)已就緒
xhr.status屬性: 服務(wù)器響應(yīng)的狀態(tài)碼
200: 響應(yīng)成功
401 請求未攜帶token/無效/超時(shí)
403 Forbidden 賬號權(quán)限不夠
404: Not found請求資源不存在
當(dāng)readyState變化時(shí),將觸發(fā)onreadystatechange事件執(zhí)行其回調(diào)函數(shù)
注意: readyState僅僅是針對請求與響應(yīng)的狀態(tài)碼淘太,獲取資源是否成功取決于status狀態(tài)
xhr.responseText: 獲取到JSON類型的字符串?dāng)?shù)據(jù)
xhr.responseXML: 獲取XML數(shù)據(jù)
POST請求下姻僧,send方法的參數(shù)格式: name=tom&password=123;
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded);
POST請求方式必須設(shè)置這個(gè)請求頭信息,目的是將請求體中的數(shù)據(jù)(name=tom&password=123)轉(zhuǎn)換成鍵值對蒲牧,
這樣后端接收到name=tom&password=123這樣的數(shù)據(jù)才知道這是一個(gè)POST方式傳過來的數(shù)據(jù)
封裝思路: 實(shí)現(xiàn)似于jQuery的調(diào)用方式
function $(){
return {
a: 1,
b: 2
}
}
console.log( $().a ) // $()得到返回的對象撇贺,對象.a 獲取到1
---------------------------------------------------------------------
var $ = (function(){
return {
a: 1,
b: 2
}
})();
console.log( $.a ); // 1
封裝ajax
var $ = (function(){
// new ActiveXObject用于IE5,6
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
if(!xhr){
throw new Error('您的瀏覽器不支持異步發(fā)起HTTP請求');
}
function packAjax(options){
var opt = options || {},
type = (opt.type || 'GET' ).toUpperCase(),
async = opt.async || true,
url = opt.url,
data = opt.data || null,
error = opt.error || function(){}, // 失敗執(zhí)行的函數(shù)
success = opt.success || function(){}, // 成功執(zhí)行的函數(shù)
complete = opt.complete || function(){}; // 不管成功or失敗都會(huì)執(zhí)行的函數(shù)
if(!url){
throw new Error('您沒有填寫URL');
}
xhr.open(type, url, async);
if(type==='POST'){
xhr.setReqeustHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.send(type === 'GET' ? null: formatDatas(data)); // get請求方式send()傳空;
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
success(JSON.parse(xhr.responseText));
complete();
}
if(xhr.status === 404){
error();
complete();
}
}
}
function formatDatas(obj){
var str = '';
for(var key in obj){
str += 'key'+'='+obj[key]+'&';
}
str.replace(/&$/,''); // 最后多一個(gè)&, &結(jié)尾替換空字符
return str; // name=tom&password=123
}
return {
ajax: function(options){
packAjax(options);
},
post: function(url, data, callback){
packAjax({
type:'POST',
url,
data,
success:callback
})
},
get: function(url,callback){
packAjax({
type: 'GET',
url,
success: callback
})
}
}
})();
// $.ajax({
// type: 'POST',
// url:'http://....',
// data: {
// name: 'tom',
// password: 123
// },
// success:function(res){
// console.log(res);
// }
// })
// $.post({
// url:'http://....',
// data: {
// name: 'tom',
// password: 123
// },
// success:function(res){
// console.log(res);
// }
// })
$.get({
url:'http://....?name=tom?password=123',
success:function(res){
console.log(res);
}
})