JavaScript로 모든 API 호출을 시도해 보셨나요? 여기 그것을 할 수 있는 방법이 있습니다

PHPz
풀어 주다: 2024-07-18 08:03:09
원래의
411명이 탐색했습니다.

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

API 호출은 최신 웹 개발의 핵심 부분입니다. JavaScript는 이 작업을 수행하는 여러 가지 방법을 제공하며 각 방법에는 고유한 장점과 단점이 있습니다. 이 글에서는 프로젝트에서 사용할 수 있는 JavaScript로 API를 호출하는 네 가지 주요 방법을 소개합니다.

XMLHttp요청(XHR)

XMLHttpRequest(XHR)는 API를 호출하는 전통적인 방법이며 모든 브라우저 버전에서 지원됩니다. 이 방법은 신뢰할 수 있고 널리 사용되지만 구문을 읽고 유지하는 것이 때로는 더 어려울 수 있습니다.

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();
로그인 후 복사

API 가져오기

Fetch API는 약속을 기반으로 API를 호출하는 보다 현대적이고 간단한 방법입니다. 비동기 작업을 지원하며 async 및 Wait를 사용하여 쉽게 확장할 수 있습니다.

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
로그인 후 복사

비동기 및 대기 사용

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는 API 호출을 위한 간단하고 일관된 인터페이스를 제공하는 인기 있는 HTTP 요청 라이브러리입니다. 먼저 npm 또는 Yarn을 사용하여 설치해야 합니다.
npm 설치 축
아니면
실 추가 축

그런 다음 Axios를 사용하여 API 호출을 수행할 수 있습니다.

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
    });
로그인 후 복사

비동기 및 대기 사용:

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는 jQuery 라이브러리를 사용하여 API를 호출하는 방법입니다. jQuery는 오늘날 덜 일반적으로 사용되지만 여전히 오래된 프로젝트에 나타납니다.

<!-- 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>
로그인 후 복사

사진 출처:
라코지, 그렉. 웹사이트 디자인 도서. 온라인. 에서: Unsplash. 2016. 출처: https://unsplash.com/photos/html-css-book-vw3Ahg4x1tY. [cit. 2024-07-16].

위 내용은 JavaScript로 모든 API 호출을 시도해 보셨나요? 여기 그것을 할 수 있는 방법이 있습니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!