关于前端:在-JS-中如何使用-Ajax-来进行请求

3次阅读

共计 5346 个字符,预计需要花费 14 分钟才能阅读完成。

作者:Danny Markov
译者:前端小智
起源:tutorialzine

点赞再看 ,微信搜寻【大迁世界】 关注这个没有大厂背景,但有着一股向上踊跃心态人。本文 GitHub https://github.com/qq44924588… 上曾经收录,文章的已分类,也整顿了很多我的文档,和教程材料。**

最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。

github 地址:https://github.com/qq44924588…

在本教程中,咱们将学习如何应用 JS 进行 AJAX 调用。

1.AJAX

术语 AJAX 示意 异步的 JavaScript 和 XML

AJAX 在 JS 中用于收回异步网络申请来获取资源。当然,不像名称所暗示的那样,资源并不局限于 XML,还用于获取 JSON、HTML 或纯文本等资源。

有多种办法能够收回网络申请并从服务器获取数据。咱们将一一介绍。

2.XMLHttpRequest

XMLHttpRequest对象(简称XHR)在较早的时候用于从服务器异步检索数据。

之所以应用XML,是因为它首先用于检索 XML 数据。当初,它也能够用来检索 JSON, HTML 或纯文本。

事例 2.1: GET

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 对象。

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 注释作为字符串发送。

2.3 XMLHttpRequest vs Fetch

晚期的开发人员,曾经应用了好多年的 XMLHttpRequest来申请数据了。古代的 fetch API 容许咱们收回相似于 XMLHttpRequest(XHR) 的网络申请。次要区别在于fetch() API 应用Promises,它使 API 更简略,更简洁,防止了回调天堂。

3. Fetch API

Fetch 是一个用于进行 AJAX 调用的原生 JavaScript API,它失去了大多数浏览器的反对,当初失去了宽泛的利用。

3.1 API 用法

fetch(url, options)
    .then(response => {// handle response data})
    .catch(err => {// handle errors});

API 参数

fetch() API 有两个参数

  1. url是必填参数,它是您要获取的资源的门路。
  2. options是一个可选参数。不须要提供这个参数来收回简略的 GET 申请。

    • method: GET | POST | PUT | DELETE | PATCH
    • headers: 申请头,如 {“Content-type”:“application/json; charset=UTF-8”}

      • mode: cors | no-cors | same-origin | navigate
      • cache: default | reload | no-cache
      • body: 个别用于 POST 申请

API 返回 Promise 对象

fetch() API 返回一个 promise 对象。

  • 如果存在网络谬误,则将回绝,这会在 .catch() 块中解决。
  • 如果来自服务器的响应带有任何状态码 (如200404500),则 promise 将被解析。响应对象能够在.then() 块中解决。

错误处理

请留神,对于胜利的响应,咱们冀望状态代码为200(失常状态),然而即便响应带有谬误状态代码(例如404(未找到资源)和500(外部服务器谬误)),fetch() API 的状态也是 resolved,咱们须要在.then() 块中显式地解决那些。

咱们能够在response 对象中看到 HTTP 状态:

  • HTTP 状态码,例如 200。
  • ok –布尔值,如果 HTTP 状态代码为 200-299,则为true

3.3 示例:GET

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}

在下面的代码中须要留神两件事:

  1. fetch API 返回一个 promise 对象,咱们能够将其调配给变量并稍后执行。
  2. 咱们还必须调用 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)

3.3 示例:POST

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}

在下面的代码中须要留神两件事:-

  1. POST申请相似于 GET 申请。咱们还须要在fetch() API 的第二个参数中发送methodbodyheaders 属性。
  2. 咱们必须须要应用 JSON.stringify() 将对象转成字符串申请body 参数

4.Axios API

Axios API 十分相似于 fetch API,只是做了一些改良。我集体更喜爱应用 Axios API 而不是fetch() API,起因如下:

  • 为 GET 申请提供 axios.get(),为 POST 申请提供 axios.post()等提供不同的办法,这样使咱们的代码更简洁。
  • 将响应代码(例如 404、500)视为能够在 catch() 块中解决的谬误,因而咱们无需显式解决这些谬误。
  • 它提供了与 IE11 等旧浏览器的向后兼容性
  • 它将响应作为 JSON 对象返回,因而咱们无需进行任何解析

4.1 示例:GET

// 在 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,咱们必须显式解决它们。

4.2 示例:POST

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。

正文完
 0