一、Ajax
Ajax:( “Asynchronous JavaScript and XML”(異步JavaScript和XML)的縮寫)是一組Web開發(fā)技術,Ajax不是一種技術,而是一個編程概念。AJAX 這個詞就成為 JavaScript 腳本發(fā)起 HTTP 通信的代名詞,也就是說,只要用腳本發(fā)起通信,就可以叫做 AJAX 通信。
技術實現(xiàn)
- 用于演示的HTML(或 XHTML)和 CSS
- 文檔對象模型(DOM),用于動態(tài)顯示數(shù)據(jù)并與之交互
- 用于數(shù)據(jù)交換的 JSON 或 XML,以及用于 XML 操作的 XSLT
- 用于異步通信的XMLHttpRequest對象
- 將這些技術結合在一起的JavaScript
原生javascript示例
GET 方法
使用 GET 方法的簡單 Ajax 請求的示例,用JavaScript編寫
// 這是客戶端腳本.
// 初始化HTTP請求.
let xhr = new XMLHttpRequest();
// 定義請求
xhr.open('GET', 'send-ajax-data.php',true);//true表示異步,false表示同步,默認為 true,指示是否異步執(zhí)行操作。
// 跟蹤請求的狀態(tài)更改.
xhr.onreadystatechange = function () {
const DONE = 4; // readyState 4 表示請求已完成.
const OK = 200; // 狀態(tài) 200 是一個成功返回.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.responseText); // '這是輸出.'
} else {
console.log('Error: ' + xhr.status); // 請求期間出錯.
}
}
};
//發(fā)送發(fā)送到 send-ajax-data.php
xhr.send(null);
POST方法
使用 POST 方法的簡單 Ajax 請求的示例,用JavaScript編寫
const xhr = new XMLHttpRequest();
xhr.open("POST", 'send-ajax-data2.php', true);
//隨請求一起發(fā)送正確的標頭信息
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = () => { // 在狀態(tài)更改時調(diào)用函數(shù).
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// 請求已完成。在這里進行處理.
console.log(xhr.responseText); // '這是輸出.'
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
JQUERY方法示例
GET方法
$.get("send-ajax-data.php",function(data){
console.log(data);
});
$.get("send-ajax-data.php", { name: "John", time: "2pm" } ,function(data){
console.log(data);
});
或:
$.ajax({
type: 'GET',
url: 'send-ajax-data.php',
data: { name: "John", time: "2pm" } ,//url請求參數(shù):可選
success: function (resp) {
console.log(resp);
},
error: function () {}
});
GET JSON方法
//只能接受 json格式的數(shù)據(jù)
$.getJSON('send-ajax-data2.php', function (data) {
console.log(data);
});
POST JSON方法
$.post("test.php", { name: "John", time: "2pm" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
或:
var data = {
"name": "Ajax中文網(wǎng)",
"url": "http://ajax.p2hp.com/"
};
$.ajax({
type: 'POST',
url: 'send-ajax-data3.php',
data: data,
dataType: "json",//dataType:"jsonp",//jsonp是跨域方式
async: true,//是否異步(ajax默認是異步的)
success: function (resp) {
console.log(resp);
},
error: function () {}
});
二、Fetch(代替品)
Fetch是一個新的原生JavaScript API。 根據(jù)谷歌開發(fā)者文檔,“Fetch使得發(fā)出網(wǎng)絡請求和處理響應比使用舊的XMLHttpRequest更容易
GET方法
ES6(Promise)
fetch('send-ajax-data.php')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));
fetch('/mock/xxxxx').then(res => {
console.log(res)
//是一個綜合各種方法的對象,并不是請求的數(shù)據(jù)? ?和axios的區(qū)別(fetch的返回值是一個promise對象)
if(res.ok){
res.json().then(data=>{
console.log(data)?//json數(shù)據(jù)??和axios的區(qū)別
})
? }?
? ? ? ? }).catch(err => {
? ? ? ? ? ? console.log(err)
? ? ? ? })
ES7(async/await)
async function doAjax1() {
try {
const res = await fetch('send-ajax-data2.php');
if (!res.ok) {
}
//const data = await res.text();
const data = await res.json();
console.log(data);
} catch (error) {
console.log('Error:' + error);
}
}
doAjax1();
POST方法
async function doAjax1() {
try {
var data = {
name: 'John',
age: 30
};
const res = await fetch('send-ajax-data2.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!res.ok) {}
//const dataresp = await res.text();
const dataresp = await res.json();
console.log(dataresp);
} catch (error) {
console.log('Error:' + error);
}
}
doAjax1();
const arr1 = [{name: "haha",detail:"123"}];
fetch("url", {
method: "post",
credentials: "include",//默認為omit,忽略的意思,
//也就是不帶cookie還有兩個參數(shù),same-origin,
//意思就是同源請求帶cookie;include,表示無論跨域還是同源請求都會帶cookie
headers: {//設置請求的頭部信息 "
? ? ?"Content-Type": "application/json",
? ? "Accept":"allication/json",
} //將arr1對象序列化成json字符串
body: JSON.stringify(arr1)//向服務端傳入json數(shù)據(jù)
}).then(res) {
console.log(res)//是一個綜合各種方法的對象,并不是請求的數(shù)據(jù) 和axios的區(qū)別
if(res.ok){
res.json().then(data=>{
console.log(data) //json數(shù)據(jù) 和axios的區(qū)別
})
}
}).catch(err => {
console.log(err)
})
總結
典型的 fetch 請求由兩個?await
?調(diào)用組成:
let response = await fetch(url, options); // 解析 response header
let result = await response.json(); // 將 body 讀取為 json
或者以 promise 形式:
fetch(url, options)
.then(response => response.json())
.then(result => /* process result */)
Fetch依賴于JavaScript promises。
Fetch規(guī)范在以下幾個方面與 Ajax 不同:
從 fetch()返回的Promise不會在 HTTP 錯誤狀態(tài)下拒絕,即使響應是 HTTP 404 或 500。相反,一旦服務器使用標頭進行響應,Promise 就會正常解析(如果響應不在 200–299 范圍內(nèi),則響應的 ok 屬性設置為 false),并且只有在網(wǎng)絡出現(xiàn)故障或有任何阻止請求完成時才會拒絕。 fetch()不會發(fā)送跨域 Cookie,除非您設置了憑據(jù)初始化選項(credentials init option)。
fetch號稱是AJAX的替代品,是在ES6出現(xiàn)的,使用了ES6中的promise對象。Fetch是基于promise設計的。Fetch的代碼結構比起ajax簡單多了,參數(shù)有點像jQuery ajax。
注意:fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
三、Axios
Axios 是一個基于?promise?網(wǎng)絡請求庫,作用于node.js?和瀏覽器中。 它是?isomorphic?的(即同一套代碼可以運行在瀏覽器和node.js中)。在服務端它使用原生 node.js?http
?模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。
執(zhí)行?GET
?請求
// 為給定 ID 的 user 創(chuàng)建請求
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);
});
執(zhí)行?POST
?請求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
執(zhí)行多個并發(fā)請求
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) {
// 兩個請求現(xiàn)在都執(zhí)行完成
}));
或者以??形式處理多個請求
在 Axios 中,可以使用?axios.all?和?axios.spread?來處理多個并發(fā)的請求:
const axios = require('axios');
// 創(chuàng)建多個請求
const request1 = axios.get('https://api.example.com/data1');
const request2 = axios.get('https://api.example.com/data2');
// 并發(fā)發(fā)送多個請求
axios.all([request1, request2])
.then(axios.spread((response1, response2) => {
// 處理各個請求的響應
console.log(response1.data);
console.log(response2.data);
}))
.catch(error => {
// 處理錯誤
console.error(error);
});
可以看到,在?.then?方法中使用了?axios.spread?函數(shù)將多個請求的響應結果進行解構,通過多個參數(shù)分別接收各個請求的響應。可以根據(jù)實際情況命名這些參數(shù),并通過?response1.data、response2.data?等方式獲取各個請求的響應數(shù)據(jù)。
攔截請求和響應
Axios 中,可以使用攔截器來攔截請求和響應,并在其被發(fā)送或接收之前進行一些額外的處理,可以通過?axios.interceptors?對象來添加攔截器。
// 添加請求攔截器
axios.interceptors.request.use(config => {
// 在發(fā)送請求之前做一些處理
console.log('請求攔截器');
// 修改請求配置
config.headers['Authorization'] = 'Bearer token';
return config;
}, error => {
// 處理請求錯誤
console.error('請求出錯:', error);
});
// 添加響應攔截器
axios.interceptors.response.use(response => {
// 在接收到響應數(shù)據(jù)之前做一些處理
console.log('響應攔截器');
// 修改響應數(shù)據(jù)
response.data = { ...response.data, extraField: 'Extra Value' };
return response;
}, error => {
// 處理響應錯誤
console.error('響應出錯:', error);
});
// 發(fā)送請求
axios.get('https://api.example.com/data')
.then(response => {
// 處理成功響應
console.log(response.data);
})
.catch(error => {
// 處理請求或響應錯誤
console.error(error);
});
這里首先使用?axios.interceptors.request.use?方法添加了一個請求攔截器。該攔截器在發(fā)送請求之前被調(diào)用,并接收請求配置對象?config?作為參數(shù)。可以對請求配置進行修改,如添加請求頭信息。最后,要確保返回修改后的配置對象。
接下來,使用?axios.interceptors.response.use?方法添加了一個響應攔截器。該攔截器在接收到響應數(shù)據(jù)之前被調(diào)用,并接收響應對象?response?作為參數(shù)。可以對響應數(shù)據(jù)進行修改,如添加額外的字段。同樣,要確保返回修改后的響應對象。
取消請求
在 Axios 中,可以使用取消令牌(cancel token)來取消請求。取消令牌是一個對象,它表示一個具體的取消操作,并允許在需要時中止請求。
// 創(chuàng)建一個取消令牌源
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 發(fā)送請求
axios.get('/api/data', {
cancelToken: source.token
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('請求已被取消:', error.message);
} else {
console.error(error);
}
});
// 取消請求
source.cancel('取消請求的原因');
這里,先創(chuàng)建了一個取消令牌源?source。然后,發(fā)送 GET 請求時將?cancelToken?配置選項設置為?source.token,即將取消令牌與該請求關聯(lián)起來。當需要取消請求時,調(diào)用?source.cancel()?方法,并傳入取消請求的原因作為參數(shù)。
在請求的?.catch()?方法中,我們使用?axios.isCancel(error)?來判斷捕獲的錯誤是否是一個已取消的請求。如果是取消請求導致的錯誤,則會打印出 '請求已被取消' 的提示信息。否則,將打印出其他類型的錯誤。
請求超時
可以使用?timeout?配置選項設置 Axios 請求的超時時間,這個選項指定了請求在多少毫秒后如果沒有得到響應就會超時。
axios.get('/api/data', {
timeout: 5000 // 設置超時時間為5秒
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
發(fā)送了一個 GET 請求,并在配置選項中設置了?timeout?為 5000 毫秒(即 5 秒)。如果請求在 5 秒內(nèi)沒有得到響應,就會觸發(fā)超時錯誤。在超時錯誤的情況下,請求會被自動取消,并且進入?.catch()?分支。您可以根據(jù)需要進行錯誤處理。
注意,如果不設置?timeout?選項,默認情況下 Axios 請求是沒有超時限制的。
?axios和fetch的區(qū)別
axios("http://xxx/xxx.json?a=123'").then((res)=>{
console.log(res)//這里的res是響應結果
})
fetch("http://www.baidu.com").then((res)=>{
console.log(res);//是一個綜合各種方法的對象(fetch的返回值是一個promise對象),并不是請求的數(shù)據(jù)
//還需要res.json().then(data=>{}
})
axios :
- 從瀏覽器中創(chuàng)建 XMLHttpRequest
- 從 node.js 發(fā)出 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉(zhuǎn)換請求和響應數(shù)據(jù)
- 自動轉(zhuǎn)換JSON數(shù)據(jù)
- 客戶端支持防止CSRF/XSRF
fetch:
? ? ? ?符合關注分離,沒有將輸入、輸出和用事件來跟蹤的狀態(tài)混雜在一個對象里,? ?更加底層,提供的API豐富(request, response),?脫離了XHR,是ES規(guī)范里新的實現(xiàn)方式
- fetchtch只對網(wǎng)絡請求報錯,對400,500都當做成功的請求,需要封裝去處理
- fetch默認不會帶cookie,需要添加配置項
- fetch不支持abort,不支持超時控制,使用setTimeout及Promise.reject的實現(xiàn)的超時控制? ? ? ? 并不能阻止請求過程繼續(xù)在后臺運行,造成了量的浪費
- fetch沒有辦法原生監(jiān)測請求的進度,而XHR可以
- fetch的返回值是一個promise對象
ajax和fetch的區(qū)別 :
- ajax是理用XMLHttpRequest對象來請求數(shù)據(jù)的,而fetch是window的一個方法
- ajax基于原生的XHR開發(fā),XHR本身的架構不清晰,已經(jīng)有了fetch的替代方案
- fetch比較與ajax有著更好更方便的寫法
- fetch只對網(wǎng)絡請求報錯,對400,500都當做成功的請求,需要封裝去處理
- fetch沒有辦法原生監(jiān)測請求的進度,而XHR可以
四、Get
GET請求通常用于從服務器請求數(shù)據(jù)。例如,當你在瀏覽器中輸入一個網(wǎng)址并按Enter鍵時,你實際上發(fā)送了一個GET請求來獲取網(wǎng)頁的內(nèi)容。
// 發(fā)起GET請求
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
五、Post
POST請求通常用于提交數(shù)據(jù)到服務器。例如,當你在網(wǎng)頁上填寫一個表單并提交時,你實際上發(fā)送了一個POST請求來發(fā)送表單數(shù)據(jù)。
// 要提交的數(shù)據(jù)
const data = {
username: 'john_doe',
password: 'secret123'
};
// 發(fā)起POST請求
fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
get與post區(qū)別
GET和POST請求在HTTP協(xié)議中用于向服務器發(fā)送數(shù)據(jù),但它們在使用方式、數(shù)據(jù)傳輸和安全性等方面存在一些重要的區(qū)別。文章來源:http://www.zghlxwxcb.cn/news/detail-814789.html
- 數(shù)據(jù)傳輸方式:GET請求的數(shù)據(jù)會被附加在URL之后,而POST請求的數(shù)據(jù)則包含在請求體中。這意味著GET請求的數(shù)據(jù)會顯示在瀏覽器地址欄中,而POST請求的數(shù)據(jù)則不會。
- 數(shù)據(jù)量限制:由于GET請求的數(shù)據(jù)附加在URL中,因此對數(shù)據(jù)量有一定的限制,這取決于瀏覽器和代理的設置。而POST請求沒有這種限制,可以發(fā)送大量數(shù)據(jù)。
- 安全性:由于GET請求的數(shù)據(jù)在URL中傳輸,因此不太安全,不適合傳輸敏感數(shù)據(jù)或大量數(shù)據(jù)。而POST請求的數(shù)據(jù)在請求體中傳輸,相對更安全。
- 緩存機制:GET請求可以被瀏覽器緩存,而POST請求則不能。
- 目的:GET請求主要用于從服務器獲取數(shù)據(jù),而POST請求主要用于向服務器提交數(shù)據(jù)。
- 參數(shù)傳遞:GET請求的參數(shù)在URL中傳遞,而POST請求的參數(shù)在請求體中傳遞。
- 效率:由于GET請求可以直接從瀏覽器地址欄中輸入,并且支持刷新和后退操作,因此執(zhí)行效率較高。而POST請求不支持刷新和后退操作,需要重新發(fā)送數(shù)據(jù)。
簡單來說,get 和post 是 HTTP 請求中最常用的兩種請求方法。get是用來獲取數(shù)據(jù),?post是用來提交數(shù)據(jù)?。get 在url?問號后面攜帶參數(shù),不安全;post通常在請求體內(nèi)攜帶參數(shù),相對get安全些。get具有緩存功能 ,post沒有緩存功能。文章來源地址http://www.zghlxwxcb.cn/news/detail-814789.html
到了這里,關于前端請求數(shù)據(jù)方法 —— Ajax、Fetch、Axios、Get、Post的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!