Home > Article > Web Front-end > A brief discussion on how to make AJAX calls and requests using JavaScript
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.
#In this tutorial, we will learn how to make AJAX calls using JS.
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.
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.
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 usingJSON.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
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 thatfetch() API uses
Promises, which makes the API simpler and more concise and avoids callback hell.
3. Fetch API
Fetch is a native JavaScript API for making AJAX calls. It is supported by most browsers and is now widely used. application.
fetch(url, options) .then(response => { // handle response data }) .catch(err => { // handle errors });API parameters
fetch() The API has two parameters
1 andurl
are required parameters, which are the paths to the resources you want to obtain.2,
options
method: GET | POST | PUT | DELETE | PATCH
headers: Request headers, such as
{ “Content-type”: “application/json; charset=UTF-8” }
body: Generally used for POST requests
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
500
), the promise will be resolved. Response objects can be handled in
Error handling
Please note that for a successful response we expect a status code of
200(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,
if the HTTP status code is 200-299.
<pre class="brush:js;toolbar:false;">const getTodoItem = fetch(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;)
.then(response => response.json())
.catch(err => console.error(err));
getTodoItem.then(response => console.log(response));</pre><pre class="brush:js;toolbar:false;">Response
{ userId: 1, id: 1, title: "delectus aut autem", 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 Let’s take a look at what happens when an HTTP
GET
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 4We 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()
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 Example: 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}
在上面的代码中需要注意两件事:-
POST
请求类似于GET
请求。 我们还需要在fetch()
API的第二个参数中发送method
,body
和headers
属性。
我们必须需要使用 JSON.stringify()
将对象转成字符串请求body
参数
Axios API非常类似于fetch API,只是做了一些改进。我个人更喜欢使用Axios API而不是fetch()
API,原因如下:
axios.get()
,为 POST 请求提供 axios.post()
等提供不同的方法,这样使我们的代码更简洁。catch()
块中处理的错误,因此我们无需显式处理这些错误。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不同。
更多编程相关知识,请访问:编程视频!!
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!