浅谈使用JavaScript如何进行AJAX调用和请求


本文摘自PHP中文网,作者青灯夜游,侵删。

Ajax是一种用于创建更好更快以及交互性更强的Web应用程序的技术,本篇文章给大家一下如何使用JavaScript进行AJAX调用和请求的方法。

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

1.AJAX

术语AJAX 表示 异步的 JavaScript 和 XML

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

有多种方法可以发出网络请求并从服务器获取数据。 我们将一一介绍。

2.XMLHttpRequest

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

之所以使用XML,是因为它首先用于检索XML数据。现在,它也可以用来检索JSON, HTML或纯文本。

事例 2.1: GET

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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用法

1

2

3

4

5

6

7

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 ?C布尔值,如果HTTP状态代码为200-299,则为true

3.2 示例:GET

1

2

3

4

5

const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1')

  .then(response => response.json())

  .catch(err => console.error(err));

 

getTodoItem.then(response => console.log(response));

1

2

3

Response

 

 { userId: 1, id: 1, title: "delectus aut autem", completed: false }

在上面的代码中需要注意两件事:

  • fetch API返回一个promise对象,我们可以将其分配给变量并稍后执行。

  • 我们还必须调用response.json()将响应对象转换为JSON

错误处理

我们来看看当HTTP GET请求抛出500错误时会发生什么:

1

2

3

4

5

6

7

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));

1

2

Inside first then block

? ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4

我们看到,即使API抛出500错误,它仍然会首先进入then()块,在该块中它无法解析错误JSON并抛出catch()块捕获的错误。

这意味着如果我们使用fetch()API,则需要像这样显式地处理此类错误:-

1

2

3

4

5

6

7

8

9

10

11

12

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;

}

1

? Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)

3.3 示例:POST

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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))

1

2

Response

? {completed: true, title: "new todo item", userId: 1, id: 201}

在上面的代码中需要注意两件事:-

  • POST请求类似于GET请求。 我们还需要在fetch() API的第二个参数中发送methodbodyheaders 属性。

  • 我们必须需要使用 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

1

2

3

4

5

6

// 在chrome控制台中引入脚本的方法

 

var script = document.createElement('script');

script.type = 'text/javascript';

script.src = 'https://unpkg.com/axios/dist/axios.min.js';

document.head.appendChild(script);

1

2

3

axios.get('https://jsonplaceholder.typicode.com/todos/1')

  .then(response => console.log(response.data))

  .catch(err => console.error(err));

1

2

Response

{ userId: 1, id: 1, title: "delectus aut autem", completed: false }

我们可以看到,我们直接使用response获得响应数据。数据没有任何解析对象,不像fetch() API。

错误处理

1

2

3

axios.get('http://httpstat.us/500')

  .then(response => console.log(response.data))

  .catch(err => console.error("Inside catch block:", err));

1

Inside catch block: Error: Network Error

我们看到,500错误也被catch()块捕获,不像fetch() API,我们必须显式处理它们。

4.2 示例:POST

1

2

3

4

5

6

7

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))

1

{completed: true, title: "new todo item", userId: 1, id: 201}

我们看到POST方法非常简短,可以直接传递请求主体参数,这与fetch()API不同。

更多编程相关知识,请访问:编程视频!!

以上就是浅谈使用JavaScript如何进行AJAX调用和请求的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

js怎么格式化日期

javascript里的push方法有什么用

javascript中对象怎么转换为字符串

javascript输出语句有哪些

js面试高频题 原型与原型链

五个超好用的array.from()用途(详解)

javascript绑定事件的方法有哪些

javascript自定义函数的写法是什么

什么是javascript引擎

javascript怎样修改div内容

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...