日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

axios与ajax对比,AjAX 步骤和对比fetch和axios

發布時間:2023/12/20 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 axios与ajax对比,AjAX 步骤和对比fetch和axios 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是ajax

AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。php

AJAX 不是新的編程語言,而是一種使用現有標準的新方法。html

AJAX 是與服務器交換數據并更新部分網頁的藝術,在不從新加載整個頁面的狀況下。node

ajax使用步驟

第一步,建立xmlhttprequest對象,ios

var xmlhttp =new XMLHttpRequest();ajax

XMLHttpRequest對象用來和服務器交換數據。chrome

var xhttp;

if (window.XMLHttpRequest) {

//現代主流瀏覽器

xhttp = new XMLHttpRequest();

} else {

// 針對瀏覽器,好比IE5或IE6

xhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

復制代碼

第二步,使用xmlhttprequest對象的open()和send()方法發送資源請求給服務器。數據庫

xmlhttp.open(method,url,async) method包括get編程

和post,url主要是文件或資源的路徑,async參數為true(表明異步)或者false(表明同步)json

xhttp.send();使用get方法發送請求到服務器。axios

xhttp.send(string);使用post方法發送請求到服務器。

post 發送請求何時可以使用呢?

(1)更新一個文件或者數據庫的時候。

(2)發送大量數據到服務器,由于post請求沒有字符限制。

(3)發送用戶輸入的加密數據。

get例子:

xhttp.open("GET", "ajax_info.txt", true);

xhttp.open("GET", "index.html", true);

xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);xhttp.send()

復制代碼

post例子

xhttp.open("POST", "demo_post.asp", true);

xhttp.send();

復制代碼

post表單數據須要使用xmlhttprequest對象的setRequestHeader方法增長一個HTTP頭。

post表單例子

xhttp.open("POST", "ajax_test.aspx", true);

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhttp.send("fname=Henry&lname=Ford");

復制代碼

async=true 當服務器準備響應時將執行onreadystatechange函數。

xhttp.onreadystatechange = function() {

if (xhttp.readyState == 4 && xhttp.status == 200) {

document.getElementById("demo").innerHTML = xhttp.responseText;

}

};

xhttp.open("GET", "index.aspx", true);

xhttp.send();

復制代碼

asyn=false 則將不須要寫onreadystatechange函數,直接在send后面寫上執行代碼。

xhttp.open("GET", "index.aspx", false);

xhttp.send();

document.getElementById("demo").innerHTML = xhttp.responseText;

復制代碼

第三步,使用xmlhttprequest對象的responseText或responseXML屬性得到服務器的響應。

使用responseText屬性獲得服務器響應的字符串數據,使用responseXML屬性獲得服務器響應的XML數據。

document.getElementById("demo").innerHTML = xhttp.responseText;

復制代碼

第四步,onreadystatechange函數,當發送請求到服務器,咱們想要服務器響應執行一些功能就須要使用onreadystatechange函數,每次xmlhttprequest對象的readyState發生改變都會觸發onreadystatechange函數。

onreadystatechange屬性存儲一個當readyState發生改變時自動被調用的函數。 readyState屬性,XMLHttpRequest對象的狀態,改變從0到4,0表明請求未被初始化,1表明服務器鏈接成功,2請求被服務器接收,3處理請求,4請求完成而且響應準備。 status屬性,200表示成功響應,404表示頁面不存在。

在onreadystatechange事件中,服務器響應準備的時候發生,當readyState==4和status==200的時候服務器響應準備。

封裝代碼

Examples

//將對象序列化

function params(data) {

var arg = [];

for (var i in data) {

arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));

}

return arr.join('&');

}

//封裝ajax

function ajax(obj) {

//建立xhr對象;

obj.xhr = new XMLHttpRequest();

//后面隨機數防止瀏覽器緩存

obj.url = url + "?rand=" + Math.random();

//序列化對象

obj.data = params(obj.data);

//當是get請求時

if (obj.method = 'get') {

//當前面沒設置隨機數時

obj.url += obj.url.indexOf('?') == -1 ? '?' +obj.data : '&' + obj.data;

}

//異步調用

if (obj.async == true) {

//監聽響應狀態

xhr.onreadystatechange = function() {

if (xhr.readyState == 4) {

callback();

}

};

}

//啟動HTTP請求

xhr.open(obj.method, obj.url, obj.aysnc);

//當是post請求時

if(obj.method === 'post') {

//模仿表單提交

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

//發送HTTP請求-post

xhr.send(obj.data);

} else {

//發送HTTP請求-get

xhr.send(null);

}

//同步調用

if (obj.async == false) {

callback();

}

//回調函數傳參

function callback() {

if (xhr.atatus == 200) {

obj.success(xhr.responseText);

} else {

alert("失敗,失敗狀態碼:" + xhr.status);

}

}

}

document.addEventListener('click', function() {

ajax({

method: 'get',

url: 'demo3.php',

data: {

'name' = 'Lee',

'age' = 100

},

success: function(text) {

alert(text);

},

async = true

});

}, false);

復制代碼

promise封裝ajax

const getJSON = function (url) {

const promise = new Promise(function (resolve, reject) {

const handler = function () {

if (this.readyState !== 4) {

return;

}

if (this.status === 200) {

resolve(this.response);

} else {

reject(new Error(this.statusText));

}

};

const client = new XMLHttpRequest();

client.open("GET", url);

client.onreadystatechange = handler;

client.responseType = "json";

client.setRequestHeader("Accept", "application/json");

client.send();

});

return promise;

};

getJSON("/posts.json").then(function (json) {

console.log('Contents: ' + json);

}, function (error) {

console.error('出錯了', error);

});

復制代碼

2、fetch

fetch 是全局量 window 的一個方法,它的主要特色有:

一、第一個參數是URL:

二、第二個是可選參數,能夠控制不一樣配置的 init 對象

三、使用了 JavaScript Promises 來處理結果/回調:

// 鏈式處理,將異步變為相似單線程的寫法: 高級用法.

fetch('/some/url').then(function(response) {

return . //... 執行成功, 第1步...

}).then(function(returnedValue) {

// ... 執行成功, 第2步...

}).catch(function(err) {

// 中途任何地方出錯...在此處理 :(

});

復制代碼

從 fetch()返回的 Promise 將不會拒絕HTTP錯誤狀態, 即便響應是一個 HTTP 404 或 500。相反,它會正常解決 (其中ok狀態設置為false), 而且僅在網絡故障時或任何阻止請求完成時,它才會拒絕。 能夠作簡單的封裝

function checkStatus(response) {

if (response.status >= 200 && response.status < 300) {

return response

} else {

var error = new Error(response.statusText)

error.response = response

throw error

}

}

function parseJSON(response) {

return response.json()

}

fetch('/users')

.then(checkStatus)

.then(parseJSON)

.then(function(data) {

console.log('request succeeded with JSON response', data)

}).catch(function(error) {

console.log('request failed', error)

})

復制代碼

默認狀況下, fetch在服務端不會發送或接收任何 cookies, 若是站點依賴于維護一個用戶會話,則致使未經認證的請求(要發送 cookies,必須發送憑據頭). 這一點也能夠作一些處理: 若是想要在同域中自動發送cookie,加上 credentials 的 same-origin 選項

fetch(url, {

credentials: ’same-origin'

})復制代碼

same-origin值使得fetch處理Cookie與XMLHttpRequest相似。 不然,Cookie將不會被發送,致使這些請求不保留認證會話。

對于CORS請求,使用include值容許將憑據發送到其余域:

fetch(url, {

credentials: 'include'

})

復制代碼

2.axios

axios({

method: 'post',

url: '/user/12345',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

}

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

復制代碼

優缺點:

從 node.js 建立 http 請求

支持 Promise API

客戶端支持防止CSRF

提供了一些并發請求的接口(重要,方便了不少的操做)

為何要用axios?

axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它自己具備如下特征:

從瀏覽器中建立 XMLHttpRequest

從 node.js 發出 http 請求

支持 Promise API

攔截請求和響應

轉換請求和響應數據

取消請求

自動轉換JSON數據

客戶端支持防止CSRF/XSRF

總結

以上是生活随笔為你收集整理的axios与ajax对比,AjAX 步骤和对比fetch和axios的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。