Home  >  Article  >  Web Front-end  >  Have you tried all API calls in JavaScript? Here are ays to do it

Have you tried all API calls in JavaScript? Here are ays to do it

PHPz
PHPzOriginal
2024-07-18 08:03:09508browse

Have you tried all API calls in JavaScript? Here are ays to do it

API calls are a key part of modern web development. JavaScript offers several ways to accomplish this task, each with its own advantages and disadvantages. This article will introduce you to four main methods of making API calls in JavaScript that you can use in your projects.

XMLHttpRequest (XHR)

XMLHttpRequest (XHR) is a traditional way to call APIs, supported in all browser versions. This method is reliable and widely used, although its syntax can sometimes be harder to read and maintain.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(JSON.parse(xhr.responseText)); // Parse and log the response data
        } else {
            console.error('Error:', xhr.statusText); // Log any errors
        }
    }
};
xhr.send();

Fetch API

Fetch API is a more modern and simpler way to make API calls, based on promises. It supports asynchronous operations and is easy to extend using async and await.

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data)) // Log the response data
    .catch(error => console.error('Error:', error)); // Log any errors

Using async and await.

async function fetchData() {
    try {
        const response = await fetch("https://api.example.com/data");
        const data = await response.json();
        console.log(data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();

Axios

Axios is a popular library for HTTP requests that provides a simple and consistent interface for making API calls. It needs to be installed first using npm or yarn.
npm install axios
or
yarn add axios

Then you can use Axios for making API calls:

const axios = require('axios');

axios.get("https://api.example.com/data")
    .then(response => {
        console.log(response.data); // Log the response data
    })
    .catch(error => {
        console.error('Error:', error); // Log any errors
    });

Using async and await:

async function fetchData() {
    try {
        const response = await axios.get("https://api.example.com/data");
        console.log(response.data); // Log the response data
    } catch (error) {
        console.error('Error:', error); // Log any errors
    }
}
fetchData();

jQuery AJAX

jQuery AJAX is a method for making API calls using the jQuery library. Although jQuery is less commonly used today, it still appears in older projects.

<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    $.ajax({
        url: "https://api.example.com/data",
        method: "GET",
        success: function(data) {
            console.log(data); // Log the response data
        },
        error: function(error) {
            console.error('Error:', error); // Log any errors
        }
    });
});
</script>

Source photo:
RAKOZY, Greg. Website design books. Online. In: Unsplash. 2016. Available from: https://unsplash.com/photos/html-css-book-vw3Ahg4x1tY. [cit. 2024-07-16].

The above is the detailed content of Have you tried all API calls in JavaScript? Here are ays to do it. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn