Home  >  Article  >  Web Front-end  >  A brief discussion on how to make AJAX calls and requests using JavaScript

A brief discussion on how to make AJAX calls and requests using JavaScript

青灯夜游
青灯夜游forward
2021-06-23 12:04:323232browse

Ajax is a technology used to create better, faster and more interactive web applications. This article will show you how to use JavaScript to make AJAX calls and requests.

A brief discussion on how to make AJAX calls and requests using JavaScript

#In this tutorial, we will learn how to make AJAX calls using JS.

1.AJAX

The term AJAX stands for asynchronous JavaScript and XML.

AJAX is used in JS to make asynchronous network requests to obtain resources. Of course, as the name implies, resources are not limited to XML, but can also be used to obtain resources such as JSON, HTML or plain text.

There are multiple ways to make network requests and get data from the server. We will introduce them one by one.

2. data.

XML is used because it is used to retrieve XML data first. Now, it can also be used to retrieve JSON, HTML or plain text.

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

We see that to make a simple GET request, two listeners are needed to handle the request of success and failure. We also need to call the

open() and send() methods. The response from the server is stored in the responseText

variable, which is converted to a JavaScript object using

JSON.parse().

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
  })
);
We see that POST requests are similar to GET requests. We need to additionally set the request header "Content-Type" using setRequestHeader and send the JSON body as a string using JSON.stringify in the send method.

2.3 XMLHttpRequest vs Fetch

Early developers have been using

XMLHttpRequest for many years to request data . The modern fetch API allows us to make network requests similar to XMLHttpRequest (XHR)

. The main difference is that

fetch() API uses Promises, which makes the API simpler and more concise and avoids callback hell. 3. Fetch APIFetch is a native JavaScript API for making AJAX calls. It is supported by most browsers and is now widely used. application.

3.1 API usage

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

API parameters

fetch() The API has two parameters

1 and

url

are required parameters, which are the paths to the resources you want to obtain.

2, options

is an optional parameter. There is no need to provide this parameter to make a simple GET request.

method: GET | POST | PUT | DELETE | PATCH

headers: Request headers, such as { “Content-type”: “application/json; charset=UTF-8” }

  • ##mode: cors | no-cors | same-origin | navigate
  • cache: default | reload | no-cache

    body: Generally used for POST requests

    • API returns Promise object
    fetch()
  • The API returns a promise object.

Will reject if there is a network error, which is handled in the .catch()

block.

If the response from the server comes with any status code (such as 200

,
    404
  • , 500), the promise will be resolved. Response objects can be handled in
  • .then()
  • blocks. Error handlingPlease note that for a successful response we expect a status code of 200
  • (normal status), but even The response comes with an error status code (such as
404

(resource not found) and 500 (internal server error)), as is the status of the

fetch()

API #resolved, we need to handle those explicitly in the .then() block. We can see the HTTP status in the response object: HTTP status code, such as 200. ok – Boolean value,

true

if the HTTP status code is 200-299.

  • 3.2 Example: GET
  • <pre class="brush:js;toolbar:false;">const getTodoItem = fetch(&amp;#39;https://jsonplaceholder.typicode.com/todos/1&amp;#39;) .then(response =&gt; response.json()) .catch(err =&gt; console.error(err)); getTodoItem.then(response =&gt; console.log(response));</pre><pre class="brush:js;toolbar:false;">Response { userId: 1, id: 1, title: &quot;delectus aut autem&quot;, completed: false }</pre>There are two things to note in the above code:

fetch The API returns a promise object that we can assign to a variable and execute later.

We must also call
    response.json()
  • Convert the response object to JSON

  • Error handling
  • Let’s take a look at what happens when an HTTP GET

    request throws a 500 error:
  • fetch(&#39;http://httpstat.us/500&#39;) // 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
We see that even though the API throws a 500 error, It will still first enter the

then() block where it fails to parse the error JSON and throws the error caught by the catch()

block.

This means that if we use the fetch()

API, we need to handle such errors explicitly like this: -

fetch(&#39;http://httpstat.us/500&#39;)
  .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 Example: POST

fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;, {
    method: &#39;POST&#39;,
    body: JSON.stringify({
      completed: true,
      title: &#39;new todo item&#39;,
      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的第二个参数中发送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

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

var script = document.createElement(&#39;script&#39;);
script.type = &#39;text/javascript&#39;;
script.src = &#39;https://unpkg.com/axios/dist/axios.min.js&#39;;
document.head.appendChild(script);
axios.get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;)
  .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(&#39;http://httpstat.us/500&#39;)
  .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(&#39;https://jsonplaceholder.typicode.com/todos&#39;, {
      completed: true,
      title: &#39;new todo item&#39;,
      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不同。

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

The above is the detailed content of A brief discussion on how to make AJAX calls and requests using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete