一.原生js實現ajax請求:
步驟:
get請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 1.創建一個XMLHttpRequest的對象.
var xml= null ; //初始值設為空
if (XMLHttpRequest){
xml= new XMLHttpRequest; //兼容非IE6
} else {
xml= new ActiveXObject( 'Microsoft.XMLHTTP' ); //兼容IE6瀏覽器
}
//2.通過open與服務器建立連接 open(method,url,async) ;
//method包含 GET、POST、PUT方式。
//第三個參數同步(false)或者異步(true)
xml.open( 'GET' ,url, true );
//3.發送請求 send(string)
//string(參數) 僅用於post請求,GET請求不需要傳參數,如果有參數直接拼接到url中。
xml.send();
//4.狀態和響應
xml.onreadystatechange= function (){
//當readyState==4並且status==200時請求成功,否則請求失敗
if (xml.readyState==4&&xml.status==200){
//請求成功
} else {
//請求失敗
}
}
|
2.post請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//步驟同 get
var xml= null ;
var data={a:1,b:2};
if (XMLHttpRequest){
xml= new XMLHttpRequest;
} else {
xml= new ActiveXObject( 'Microsoft.XMLHTTP' )
}
xml.open( 'POST' ,url, true );
xml.send(data); //這里的data是要傳遞的參數
xml.onreadystatechange= function (){
if (xml.readyState==4&&xml.status==200){
//請求成功
} else {
//請求失敗
}
}
|
二.jq實現ajax請求:
get請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// 1.get請求
$.ajax({
type: "get" ,
url: "" ,
async: true ,
timeout:3000, //timeout:響應超時時間,非必須參數
beforeSend: function (){
//這里是發送請求之前所要進行的操作
},
success: function (){
//請求成功
},
error: function (){
//請求失敗
}
});
|
post請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
$.ajax({
type: "post" ,
url: "" ,
data:{a:1,b:2}, //需要傳遞的參數
async: true ,
timeout:3000, //timeout:響應超時時間,非必須參數
beforeSend: function (){
//這里是發送請求之前所要進行的操作
},
success: function (){
//請求成功
},
error: function (){
//請求失敗
}
});
|
三.axios請求:
首先安裝axios,
方法一:npm install axios
方法二: CDN引入 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get請求:
1
2
3
4
5
6
7
|
//1.get請求(無參數)
axios.get( 'http://www.xxx' )
.then( function (response){
//請求成功
}). catch ( function (erroe){
//請求失敗
});
|
1
2
3
4
5
6
7
|
//2.get請求(有參數)
axios.get( 'http://www.xxx?a=1&b=2' )
.then( function (response){
//請求成功
}). catch ( function (erroe){
//請求失敗
});
|
post請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
//必須引入qs對data進行stringify 安裝axios時已經安裝了qs,無需再安裝,引入即可用。
// import Qs from 'qs'
let data=Qs.stringify({a:1,b:2});
axios.post( 'http://www.xxx' ,data)
.then( function (response){
//請求成功
}). catch ( function (error){
//請求失敗
})
//4.多個請求同時發送
function axiosOne(){
return axios.get( 'http://www.url.one' )
};
function axiosTwo(){
return axios.get( 'http://www.url.two' )
};
axios.all([axiosOne(),axiosTwo()])
.then(axios.spread( function (acct, perms){
console.log(acct); //請求一的結果;
console.log(perms); //請求二的結果
}))
|