前言: Vue的使用使前端程式員主要精力放在業務上,省去了大量dom的操作。身邊的很多同僚仍然使用JQuery的ajax發送請求,使用JQuery 也就僅僅使用了封裝好的ajax,這樣給頁面的加載增加負擔,JQuery的引入使頁面的加載顯的很笨重。前端發送請求的方式很多種,不一定要再頁面上大量使用JQuery封裝的ajax,有幾種請求方式可以省去JQuery的引入進行ajax請求。下面我将進行一一介紹:
一.axios
首先需要知道:axios不是一種新的技術。
axios 是一個基于Promise 用于浏覽器和 nodejs 的 HTTP 用戶端,本質上也是對原生XHR的封裝,隻不過它是Promise的實作版本,符合最新的ES規範,有以下特點:
- 從浏覽器中建立 XMLHttpRequests
- 從 node.js 建立 http 請求
- 支援 Promise API
- 攔截請求和響應
- 轉換請求資料和響應資料
- 取消請求
- 自動轉換 JSON 資料
- 用戶端支援防禦 XSRF
使用
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
get請求
// 為給定 ID 的 user 建立請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的請求也可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
并發請求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 兩個請求現在都執行完成
}));
二.fetch
fetch是前端發展的一種新技術産物。
使用
不需要引入js,隻要引入vue.js就可以,很友善
發送請求
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
post請求傳參
fetch("http://127.0.0.1:8080/getUser",
{
method: 'POST',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
body:"id=39"
})
.then(function(resp) {
console.log(resp);
return resp.json();
})
.then(data=>{
console.log(data)
that.obj=data
})
.catch(error=>{
console.log(error)
})
三.ajax
用的比較廣泛的一種異步請求方式
如果沒有 jQuery,AJAX 程式設計還是有些難度的。
編寫正常的 AJAX 代碼并不容易,因為不同的浏覽器對 AJAX 的實作并不相同。這意味着您必須編寫額外的代碼對浏覽器進行測試。
$.ajax({
//請求方式
type : "POST",
//請求的媒體類型
contentType: "json",
//請求位址
url : "http://127.0.0.1/admin/list/",
//資料,json字元串
data : {
},
//請求成功
success : function(result) {
console.log(result);
},
//請求失敗,包含具體的錯誤資訊
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});
jQuery load()方法
jQuery load() 方法是簡單但強大的 AJAX 方法。
load() 方法從伺服器加載資料,并把傳回的資料放入被選元素中。
文法:
$(selector).load(URL,data,callback);
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部内容加載成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
jQuery $.get() 方法
文法:
$.get(URL,callback);
$("button").click(function(){
$.get(URL,function(data,status){
alert("資料: " + data + "\n狀态: " + status);
});
});
jQuery $.post() 方法
文法:
$.post(URL,data,callback);
$("button").click(function(){
$.post(URL,
{
name:"參數",
url:"http://www.runoob.com"
},
function(data,status){
alert("資料: \n" + data + "\n狀态: " + status);
});
});
四.Vue.js Ajax(vue-resource)
vue-resource
是一個通過
XMLHttpRequrest
或
JSONP
技術實作異步加載服務端資料的Vue插件
提供了一般的 HTTP請求接口和RESTful架構請求接口,并且提供了全局方法和VUe元件執行個體方法。
使用
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
get 請求
this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
document.write(res.body);
},function(){
console.log('請求失敗處理');
});
如果需要傳遞資料,可以使用 this.$http.get('get.php',{params : jsonData}) 格式,第二個參數 jsonData 就是傳到後端的資料。
this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});
post 請求
post 發送資料到後端,需要第三個參數 {emulateJSON:true}。
emulateJSON 的作用: 如果Web伺服器無法處理編碼為 application/json 的請求,你可以啟用 emulateJSON 選項。
this.$http.post('/try/ajax/demo_test_post.php',
{name:"參數",url:"http://www.runoob.com"},{emulateJSON:true}).then(function(res){
document.write(res.body);
},function(res){
console.log(res.status);
});