做者:Danny Markov
译者:前端小智
来源:tutorialzine
点赞再看,微信搜索
【大迁世界】关注这个没有大厂背景,但有着一股向上积极心态人。本文
GitHub
https://github.com/qq44924588... 上已经收录,文章的已分类,也整理了不少个人文档,和教程资料。**
最近开源了一个 Vue 组件,还不够完善,欢迎你们来一块儿完善它,也但愿你们能给个 star 支持一下,谢谢各位了。javascript
github 地址:https://github.com/qq44924588...前端
在本教程中,咱们将学习如何使用 JS 进行AJAX调用。vue
术语AJAX 表示 异步的 JavaScript 和 XML。java
AJAX 在 JS 中用于发出异步网络请求来获取资源。固然,不像名称所暗示的那样,资源并不局限于XML,还用于获取JSON、HTML或纯文本等资源。ios
有多种方法能够发出网络请求并从服务器获取数据。 咱们将一一介绍。git
XMLHttpRequest
对象(简称XHR)在较早的时候用于从服务器异步检索数据。github
之因此使用XML,是由于它首先用于检索XML数据。如今,它也能够用来检索JSON, HTML或纯文本。web
function success() { var data = JSON.parse(this.responseText) console.log(data) } function error (err) { console.log('Error Occurred:', err) } var xhr = new XMLHttpRequest() xhr.onload = success xhr.onerror = error xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1") xhr.send()
咱们看到,要发出一个简单的GET请求,须要两个侦听器来处理请求的成功和失败。咱们还须要调用open()
和send()
方法。来自服务器的响应存储在responseText
变量中,该变量使用JSON.parse()
转换为JavaScript 对象。chrome
function success() { var data = JSON.parse(this.responseText); console.log(data); } function error(err) { console.log('Error Occurred :', err); } var xhr = new XMLHttpRequest(); xhr.onload = success; xhr.onerror = error; xhr.open("POST", "https://jsonplaceholder.typicode.com/posts"); xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); xhr.send(JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }) );
咱们看到POST请求相似于GET请求。 咱们须要另外使用setRequestHeader
设置请求标头“Content-Type” ,并使用send方法中的JSON.stringify
将JSON正文做为字符串发送。json
早期的开发人员,已经使用了好多年的 XMLHttpRequest
来请求数据了。 现代的fetch API
容许咱们发出相似于XMLHttpRequest(XHR)
的网络请求。 主要区别在于fetch()
API使用Promises,它使 API更简单,更简洁,避免了回调地狱。
Fetch 是一个用于进行AJAX调用的原生 JavaScript API,它获得了大多数浏览器的支持,如今获得了普遍的应用。
fetch(url, options) .then(response => { // handle response data }) .catch(err => { // handle errors });
API参数
fetch()
API有两个参数
options
是一个可选参数。不须要提供这个参数来发出简单的GET请求。
headers: 请求头,如 { “Content-type”: “application/json; charset=UTF-8” }
API返回Promise对象
fetch()
API返回一个promise对象。
.catch()
块中处理。200
、404
、500
),则promise将被解析。响应对象能够在.then()
块中处理。错误处理
请注意,对于成功的响应,咱们指望状态代码为200
(正常状态),可是即便响应带有错误状态代码(例如404
(未找到资源)和500
(内部服务器错误)),fetch()
API 的状态也是 resolved
,咱们须要在.then()
块中显式地处理那些。
咱们能够在response
对象中看到HTTP状态:
true
。const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .catch(err => console.error(err)); getTodoItem.then(response => console.log(response));
Response { userId: 1, id: 1, title: "delectus aut autem", completed: false }
在上面的代码中须要注意两件事:
fetch
API返回一个promise对象,咱们能够将其分配给变量并稍后执行。response.json()
将响应对象转换为JSON错误处理
咱们来看看当HTTP GET
请求抛出500错误时会发生什么:
fetch('http://httpstat.us/500') // this API throw 500 error .then(response => () => { console.log("Inside first then block"); return response.json(); }) .then(json => console.log("Inside second then block", json)) .catch(err => console.error("Inside catch block:", err));
Inside first then block ➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
咱们看到,即便API抛出500错误,它仍然会首先进入then()
块,在该块中它没法解析错误JSON并抛出catch()
块捕获的错误。
这意味着若是咱们使用fetch()
API,则须要像这样显式地处理此类错误:-
fetch('http://httpstat.us/500') .then(handleErrors) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error("Inside catch block:", err)); function handleErrors(response) { if (!response.ok) { // throw error based on custom conditions on response throw Error(response.statusText); } return response; }
➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', body: JSON.stringify({ completed: true, title: 'new todo item', userId: 1 }), headers: { "Content-type": "application/json; charset=UTF-8" } }) .then(response => response.json()) .then(json => console.log(json)) .catch(err => console.log(err))
Response ➤ {completed: true, title: "new todo item", userId: 1, id: 201}
在上面的代码中须要注意两件事:-
POST
请求相似于GET
请求。 咱们还须要在fetch()
API的第二个参数中发送method
,body
和headers
属性。JSON.stringify()
将对象转成字符串请求body
参数Axios API很是相似于fetch API,只是作了一些改进。我我的更喜欢使用Axios API而不是fetch()
API,缘由以下:
axios.get()
,为 POST 请求提供 axios.post()
等提供不一样的方法,这样使咱们的代码更简洁。catch()
块中处理的错误,所以咱们无需显式处理这些错误。// 在chrome控制台中引入脚本的方法 var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://unpkg.com/axios/dist/axios.min.js'; document.head.appendChild(script);
axios.get('https://jsonplaceholder.typicode.com/todos/1') .then(response => console.log(response.data)) .catch(err => console.error(err));
Response { userId: 1, id: 1, title: "delectus aut autem", completed: false }
咱们能够看到,咱们直接使用response得到响应数据。数据没有任何解析对象,不像fetch()
API。
错误处理
axios.get('http://httpstat.us/500') .then(response => console.log(response.data)) .catch(err => console.error("Inside catch block:", err));
Inside catch block: Error: Network Error
咱们看到,500错误也被catch()
块捕获,不像fetch()
API,咱们必须显式处理它们。
axios.post('https://jsonplaceholder.typicode.com/todos', { completed: true, title: 'new todo item', userId: 1 }) .then(response => console.log(response.data)) .catch(err => console.log(err))
{completed: true, title: "new todo item", userId: 1, id: 201}
咱们看到POST方法很是简短,能够直接传递请求主体参数,这与fetch()API不一样。
代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug。
原文:https://tutorialzine.com/2017...
文章每周持续更新,能够微信搜索【大迁世界 】第一时间阅读,回复【福利】有多份前端视频等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,欢迎Star。