AJAX 및 API 실험: 초보자를 위한 종합 가이드
1. AJAX 및 API 소개
AJAX란 무엇입니까?
AJAX는 비동기 JavaScript 및 XML을 의미합니다. 전체 페이지를 다시 로드할 필요 없이 동적이고 대화형 웹 페이지를 생성하기 위해 웹 개발에 사용되는 기술입니다. AJAX를 사용하면 서버에서 데이터를 요청하고 웹페이지의 일부를 비동기적으로 업데이트할 수 있습니다. 즉, 요청이 백그라운드에서 처리되는 동안 사용자가 페이지와 계속 상호 작용할 수 있습니다.
API란 무엇입니까?
API(애플리케이션 프로그래밍 인터페이스)는 서로 다른 소프트웨어 애플리케이션이 서로 통신할 수 있도록 하는 일련의 규칙 및 정의입니다. 웹 개발의 맥락에서 API는 웹 서버와 상호 작용하고, 데이터를 검색하고, 데이터를 보내는 데 자주 사용됩니다. API는 공개(누구나 사용 가능) 또는 비공개(특정 사용자 또는 애플리케이션으로 제한)일 수 있습니다.
AJAX와 API를 함께 사용하는 이유는 무엇입니까?
AJAX와 API를 함께 사용하면 웹 애플리케이션에서 데이터를 동적으로 가져오고, 보내고, 업데이트할 수 있습니다. 이 조합을 사용하면 지속적인 페이지를 다시 로드하지 않고도 원활한 사용자 환경을 제공하는 풍부하고 반응성이 뛰어난 대화형 웹 애플리케이션을 구축할 수 있습니다.
AJAX 및 API의 실제 애플리케이션
- 소셜 미디어 피드: Twitter 및 Facebook과 같은 플랫폼은 AJAX를 사용하여 페이지를 다시 로드하지 않고도 새 게시물과 댓글을 동적으로 로드합니다.
- 날씨 애플리케이션: 날씨 앱은 API에서 실시간 날씨 데이터를 가져와 현재 상태와 예측을 표시합니다.
- 전자상거래 웹사이트: 온라인 상점은 제품 필터링, 장바구니 업데이트, 페이지 새로고침 없이 주문 처리 등의 기능을 위해 AJAX를 사용합니다.
- 지도 및 위치 서비스: Google 지도와 같은 서비스는 AJAX를 사용하여 사용자 입력에 따라 지도 타일과 위치 데이터를 동적으로 로드합니다.
2. AJAX 시작하기
비동기 JavaScript 및 XML(AJAX) 이해
AJAX는 단일 기술이 아니라 함께 작동하는 여러 기술의 조합입니다.
- JavaScript: 사용자 상호 작용을 처리하고 비동기 요청을 하는 데 사용됩니다.
- XML/JSON: 클라이언트와 서버 간 데이터 교환을 위한 형식입니다. 오늘날에는 JSON(JavaScript Object Notation)이 더 일반적으로 사용됩니다.
- HTML/CSS: 웹페이지 콘텐츠의 구조와 스타일을 지정하는 데 사용됩니다.
- DOM(Document Object Model): 웹페이지의 구조를 나타내며 JavaScript가 웹페이지와 상호작용할 수 있도록 합니다.
AJAX의 기본 개념
- 비동기 통신: AJAX를 사용하면 웹 페이지가 서버에서 비동기적으로 데이터를 보내고 받을 수 있습니다. 즉, 브라우저는 다른 작업을 계속하기 전에 서버의 응답을 기다릴 필요가 없습니다.
- 부분 페이지 업데이트: AJAX는 전체 페이지를 다시 로드하는 대신 웹페이지의 특정 부분을 업데이트하여 성능과 사용자 경험을 향상시킬 수 있습니다.
- 클라이언트-서버 통신: AJAX를 사용하면 클라이언트 측 JavaScript가 서버 측 API와 통신하여 데이터를 가져오거나 보낼 수 있습니다.
AJAX 작동 방식
- 사용자 작업: 사용자가 버튼을 클릭하거나 양식에 텍스트를 입력하는 등의 이벤트를 트리거합니다.
- JavaScript 실행: JavaScript는 이벤트를 캡처하고 XMLHttpRequest 객체를 생성합니다.
- 서버 요청: XMLHttpRequest 객체는 서버에 요청을 보냅니다.
- 서버 처리: 서버가 요청을 처리하고 클라이언트에 응답을 다시 보냅니다.
- 클라이언트 업데이트: JavaScript는 서버 응답을 수신하고 웹페이지를 동적으로 업데이트합니다.
JavaScript를 사용한 첫 번째 AJAX 요청
AJAX의 기본을 보여주기 위해 간단한 HTML 페이지를 만들고 JavaScript를 사용하여 AJAX 요청을 서버에 보내겠습니다.
단계별 가이드:
- HTML 파일 만들기:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Example</title> </head> <body> <h1>AJAX Request Example</h1> <button id="loadData">Load Data</button> <div id="dataContainer"></div> <script src="app.js"></script> </body> </html>
2.JavaScript 파일(app.js) 만들기:
document.getElementById('loadData').addEventListener('click', function() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); xhr.onload = function() { if (xhr.status === 200) { document.getElementById('dataContainer').innerHTML = xhr.responseText; } else { console.error('Failed to load data'); } }; xhr.send(); });
3.AJAX 요청 테스트:
- Open the HTML file in a web browser.
- Click the “Load Data” button to trigger the AJAX request.
- Observe the fetched data displayed in the dataContainer div
3. Understanding APIs
Definition of APIs
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. APIs define the methods and data formats that applications can use to interact with each other, making it easier to build software by providing reusable components and services.
Types of APIs
- REST (Representational State Transfer): REST APIs are the most common type of API used in web development. They are based on standard HTTP methods like GET, POST, PUT, and DELETE and are stateless, meaning each request is independent of others.
- SOAP (Simple Object Access Protocol): SOAP is a protocol for exchanging structured information in web services. It uses XML for message formatting and relies on application layer protocols like HTTP and SMTP.
- GraphQL: A newer API standard that allows clients to request exactly the data they need. Unlike REST, GraphQL uses a single endpoint and supports complex queries and mutations.
API Endpoints and Methods
- Endpoint: An endpoint is a specific URL where an API is accessed. It represents a specific function or resource within the API.
- HTTP Methods: The method used to interact with an endpoint. Common methods include:
- GET: Retrieve data from the server.
- POST: Send data to the server to create a new resource.
- PUT: Update an existing resource on the server.
- DELETE: Remove a resource from the server.
Working with JSON and XML Formats
APIs typically use JSON (JavaScript Object Notation) or XML (eXtensible Markup Language) to format data. JSON is more lightweight and easier to read, making it the preferred choice for most modern APIs.
Example JSON Response:
{ "id": 1, "title": "Example Post", "body": "This is an example of a post.", "userId": 1 }
Example XML Response:
<post> <id>1</id> <title>Example Post</title> <body>This is an example of a post.</body> <userId>1</userId> </post>
4. Making Your First AJAX Request
Setting Up a Basic HTML and JavaScript Environment
To make your first AJAX request, you need a basic HTML and JavaScript environment. Follow these steps:
- Create an HTML File:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>First AJAX Request</title> </head> <body> <h1>Fetch Data with AJAX</h1> <button id="fetchDataBtn">Fetch Data</button> <div id="dataDisplay"></div> <script src="ajax.js"></script> </body> </html>
Create a JavaScript File (ajax.js):
document.getElementById('fetchDataBtn').addEventListener('click', function() { const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true); xhr.onload = function() { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); document.getElementById('dataDisplay').innerHTML = ` <h2>${data.title}</h2> <p>${data.body}</p> `; } else { console.error('Error fetching data'); } }; xhr.onerror = function() { console.error('Request failed'); }; xhr.send(); });
3.Test the AJAX Request:
- Open the HTML file in a web browser.
- Click the “Fetch Data” button to trigger the AJAX request.
- Observe the fetched data displayed in the dataDisplay div.
Sending a GET Request Using XMLHttpRequest
The XMLHttpRequest object is used to interact with servers. It allows you to make HTTP requests to retrieve or send data without reloading the page.
Steps to Send a GET Request:
- Create an XMLHttpRequest Object: const xhr = new XMLHttpRequest();
- Open a Connection: xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
- Define a Callback Function: xhr.onload = function() { /* Handle response */ };
- Send the Request: xhr.send();
Handling Server Responses
When the server responds to an AJAX request, the response is available in the xhr.responseText property. You can use JavaScript to process this data and update the webpage dynamically.
Debugging AJAX Requests
To debug AJAX requests, use browser developer tools:
- Network Tab: Monitor HTTP requests and responses.
- Console Tab: Log errors and messages for debugging.
5. Using Fetch API for AJAX Requests
Introduction to Fetch API
The Fetch API is a modern alternative to XMLHttpRequest for making HTTP requests. It provides a more powerful and flexible feature set and returns Promises, making it easier to handle asynchronous operations.
Making GET and POST Requests with Fetch
Example of a GET Request with Fetch:
fetch('https://jsonplaceholder.typicode.com/posts/1')<br><br> .then(response => response.json())<br><br> .then(data => {<br><br> document.getElementById('dataDisplay').innerHTML = <br> <h2>${data.title}</h2> <br> <p>${data.body}</p> <br> ;<br><br> })<br><br> .catch(error => console.error('Error fetching data:', error));<br>
Example of a POST Request with Fetch:
fetch('https://jsonplaceholder.typicode.com/posts', {<br><br> method: 'POST',<br><br> headers: {<br><br> 'Content-Type': 'application/json'<br><br> },<br><br> body: JSON.stringify({<br><br> title: 'New Post',<br><br> body: 'This is a new post.',<br><br> userId: 1<br><br> })<br><br> })<br><br> .then(response => response.json())<br><br> .then(data => console.log('Post created:', data))<br><br> .catch(error => console.error('Error creating post:', error));<br>
Handling JSON Responses
The Fetch API provides a json() method to parse the response body as JSON. This method returns a Promise that resolves with the parsed JSON data.
Error Handling with Fetch
Use .catch() to handle errors in Fetch requests. This method catches any errors that occur during the fetch operation or while processing the response.
6. Interacting with RESTful APIs
What is REST?
REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs follow specific conventions for managing resources over the web.
RESTful API Conventions
- Stateless: Each request from a client to a server must contain all the information needed to understand and process the request.
- Resource-Based: Resources (such as users, posts, or products) are identified by URLs.
- Standard Methods: RESTful APIs use standard HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources.
Sending Requests to RESTful APIs
Example of Sending a GET Request to a RESTful API:
fetch('https://jsonplaceholder.typicode.com/posts')<br><br> .then(response => response.json())<br><br> .then(posts => {<br><br> posts.forEach(post => {<br><br> console.log(post.title);<br><br> });<br><br> })<br><br> .catch(error => console.error('Error fetching posts:', error));<br>
CRUD Operations with AJAX
CRUD stands for Create, Read, Update, Delete — four fundamental operations for managing data.
- Create: Use POST to add new data.
- Read: Use GET to retrieve data.
- Update: Use PUT or PATCH to modify existing data.
- Delete: Use DELETE to remove data.
Example of CRUD Operations with Fetch:
CRUD Operations with AJAX
CRUD stands for Create, Read, Update, Delete—four fundamental operations for managing data.
Create: Use POST to add new data.
Read: Use GET to retrieve data.
Update: Use PUT or PATCH to modify existing data.
Delete: Use DELETE to remove data.
Example of CRUD Operations with Fetch:
7. Advanced AJAX Techniques
Handling CORS (Cross-Origin Resource Sharing)
CORS (Cross-Origin Resource Sharing) is a security feature that restricts web pages from making requests to a different domain than the one that served the web page. To work with APIs across different domains, the server must enable CORS.
Using Promises for Better AJAX Management
Promises simplify the management of asynchronous operations in JavaScript. They provide a more readable way to handle AJAX requests compared to callbacks.
Example of Promises with Fetch:
fetch('/api/posts')<br><br> .then(response => response.json())<br><br> .then(data => console.log(data))<br><br> .catch(error => console.error('Error:', error));<br>
Working with Async/Await for Cleaner Code
Async/Await is syntactic sugar built on top of Promises, making asynchronous code easier to read and write.
Example of Async/Await:
async function fetchPosts() {<br><br> try {<br><br> const response = await fetch('/api/posts');<br><br> const data = await response.json();<br><br> console.log(data);<br><br> } catch (error) {<br><br> console.error('Error:', error);<br><br> }<br><br> } <p>fetchPosts();<br> </p>
Chaining Multiple AJAX Requests
To handle multiple AJAX requests in sequence, use Promises or Async/Await to chain requests.
Example of Chaining AJAX Requests:
fetch('/api/user')<br><br> .then(response => response.json())<br><br> .then(user => fetch(/api/posts?userId=${user.id}))<br><br> .then(response => response.json())<br><br> .then(posts => console.log(posts))<br><br> .catch(error => console.error('Error:', error));<br>
- Building a Real-World Application with AJAX and APIs
Setting Up a Sample Project
To build a real-world application, you need a backend API and a frontend interface. For this example, we’ll use a simple API to fetch weather data.
Integrating a Third-Party API (e.g., OpenWeatherMap)
- Sign Up for an API Key: Register for an API key on the OpenWeatherMap website.
- Fetch Weather Data: Use AJAX to fetch weather data based on the user’s input.
Example of Fetching Weather Data:
const apiKey = 'YOUR_API_KEY';<br><br> const city = 'London';<br><br> fetch(https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey})<br><br> .then(response => response.json())<br><br> .then(data => {<br><br> document.getElementById('weatherDisplay').innerHTML = <br> <h2>Weather in ${data.name}</h2> <br> <p>Temperature: ${(data.main.temp - 273.15).toFixed(2)}°C</p> <br> <p>Condition: ${data.weather[0].description}</p> <br> ;<br><br> })<br><br> .catch(error => console.error('Error fetching weather data:', error));<br>
Creating Dynamic and Interactive Elements with AJAX
Use JavaScript to create dynamic elements that update based on user input or server responses.
Example of Creating Dynamic Elements:
document.getElementById('searchButton').addEventListener('click', function() {<br><br> const city = document.getElementById('cityInput').value;<br><br> fetchWeatherData(city);<br><br> }); <p>function fetchWeatherData(city) {<br><br> fetch(https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey})<br><br> .then(response => response.json())<br><br> .then(data => {<br><br> document.getElementById('weatherDisplay').innerHTML = <br> <h2>Weather in ${data.name}</h2> <br> <p>Temperature: ${(data.main.temp - 273.15).toFixed(2)}°C</p> <br> <p>Condition: ${data.weather[0].description}</p> <br> ;<br><br> })<br><br> .catch(error => console.error('Error fetching weather data:', error));<br><br> }<br> </p>
Displaying Data from API Responses
Use HTML and CSS to format the data received from APIs. JavaScript allows you to manipulate the DOM and display the data dynamically.
9. Optimizing AJAX Requests
Debouncing and Throttling API Calls
Debouncing and Throttling are techniques used to limit the rate at which a function is executed. This is especially useful when working with APIs to avoid unnecessary requests.
Example of Debouncing:
function debounce(func, delay) {<br><br> let timeout;<br><br> return function(...args) {<br><br> clearTimeout(timeout);<br><br> timeout = setTimeout(() => func.apply(this, args), delay);<br><br> };<br><br> } <p>const fetchWeatherDebounced = debounce(fetchWeatherData, 300);<br><br> document.getElementById('cityInput').addEventListener('input', function() {<br><br> fetchWeatherDebounced(this.value);<br><br> });<br> </p>
Managing Request States and Loading Indicators
Use JavaScript to manage the state of your AJAX requests and provide feedback to users, such as loading indicators or error messages.
Example of Managing Request States:
function fetchWeatherData(city) {<br><br> const loader = document.getElementById('loader');<br><br> loader.style.display = 'block'; // Show loader <div class="highlight js-code-highlight"> <pre class='brush:php;toolbar:false;'>fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`) .then(response => response.json()) .then(data => { loader.style.display = 'none'; // Hide loader // Display weather data... }) .catch(error => { loader.style.display = 'none'; // Hide loader console.error('Error fetching weather data:', error); });
}
Caching API Responses
To improve performance, cache API responses using JavaScript or a service worker. This reduces the number of requests sent to the server and speeds up the application.
Example of Caching API Responses:
const cache = new Map(); <p>function fetchWeatherData(city) {<br><br> if (cache.has(city)) {<br><br> displayWeatherData(cache.get(city)); // Use cached data<br><br> } else {<br><br> fetch(https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey})<br><br> .then(response => response.json())<br><br> .then(data => {<br><br> cache.set(city, data); // Cache the response<br><br> displayWeatherData(data);<br><br> })<br><br> .catch(error => console.error('Error fetching weather data:', error));<br><br> }<br><br> }<br> </p>
Best Practices for Efficient AJAX
- Minimize Requests: Combine multiple requests into one when possible.
- Use HTTP Caching: Leverage browser caching to reduce server load.
- Optimize Data: Request only the necessary data fields.
- Handle Errors Gracefully: Provide meaningful feedback to users in case of errors.
10. Error Handling and Debugging
Common AJAX Errors and How to Fix Them
- 404 Not Found: The requested resource is not available on the server.
- 500 Internal Server Error: The server encountered an error while processing the request.
- Network Errors: Issues with internet connectivity or server availability.
Using Browser Developer Tools for Debugging
Use browser developer tools to inspect network requests, view responses, and debug JavaScript code:
- Network Tab: View all HTTP requests and responses.
- Console Tab: Log messages and errors for debugging.
Graceful Error Handling in Your Application
Provide users with clear error messages and fallback options when AJAX requests fail.
Example of Graceful Error Handling:
fetch('https://api.example.com/data')<br><br> .then(response => response.json())<br><br> .then(data => {<br><br> // Display data...<br><br> })<br><br> .catch(error => {<br><br> console.error('Error fetching data:', error);<br><br> document.getElementById('errorMessage').innerText = 'Failed to load data. Please try again later.';<br><br> });<br>
- Security Considerations for AJAX and APIs
Preventing Common Vulnerabilities (e.g., XSS, CSRF)
- XSS (Cross-Site Scripting): Sanitize user input to prevent malicious scripts from being executed.
- CSRF (Cross-Site Request Forgery): Use anti-CSRF tokens to prevent unauthorized actions.
Safeguarding API Keys and Sensitive Data
- Environment Variables: Store API keys in environment variables, not in client-side code.
- Secure Storage: Use secure storage solutions for sensitive data.
Securely Handling User Input and API Responses
- Input Validation: Validate all user input on the client and server sides.
- Content Security Policy: Implement a Content Security Policy (CSP) to mitigate XSS attacks.
12. Conclusion and Next Steps
Recap of Key Concepts
In this tutorial, you’ve learned how to use AJAX and APIs to build dynamic web applications. You explored the basics of AJAX, the Fetch API, interacting with RESTful APIs, and advanced techniques like error handling, optimization, and security.
Exploring More Advanced AJAX and API Techniques
As you continue learning, explore more advanced topics like:
- WebSockets: Real-time communication for live updates and interactive features.
- Service Workers: Offline capabilities and background synchronization.
- GraphQL: Flexible data querying for efficient API interactions.
By Peymaan Abedinpour | پیمان عابدین پور
위 내용은 AJAX 및 API 실험: 초보자를 위한 종합 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undress AI Tool
무료로 이미지를 벗다

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Node.js에서 HTTP 요청을 시작하는 세 가지 일반적인 방법이 있습니다. 1. 기본 시나리오에 적합하지만 데이터 스티칭 및 오류 모니터링의 수동 처리 및 https.get () 사용과 같은 데이터 스티치 및 오류 모니터링의 수동 처리가 필요합니다. 2.axios는 약속을 기반으로 한 타사 도서관입니다. 간결한 구문과 강력한 기능을 가지고 있으며 비동기/기다림, 자동 JSON 변환, 인터셉터 등을 지원합니다. 비동기 요청 작업을 단순화하는 것이 좋습니다. 3. 노드 페치는 약속과 간단한 구문을 기반으로 브라우저 페치와 유사한 스타일을 제공합니다.

JavaScript 데이터 유형은 원시 유형 및 기준 유형으로 나뉩니다. 원시 유형에는 문자열, 숫자, 부울, 널, 정의되지 않은 및 기호가 포함됩니다. 값은 불변이없고 값을 할당 할 때 사본이 복사되므로 서로 영향을 미치지 않습니다. 객체, 배열 및 함수와 같은 참조 유형은 메모리 주소를 저장하고 동일한 개체를 가리키는 변수는 서로 영향을 미칩니다. 타입 및 인스턴스는 유형을 결정하는 데 사용될 수 있지만 TypeofNull의 역사적 문제에주의를 기울일 수 있습니다. 이 두 가지 유형의 차이점을 이해하면보다 안정적이고 안정적인 코드를 작성하는 데 도움이 될 수 있습니다.

JavaScript의 필터 () 메소드는 모든 통과 테스트 요소를 포함하는 새로운 배열을 만드는 데 사용됩니다. 1.Filter ()는 원래 배열을 수정하지 않고 조건부 요소를 충족하는 새 배열을 반환합니다. 2. 기본 구문은 array.filter ((element) => {returnCondition;}); 3. 객체 배열은 30 세 이상의 필터링 사용자와 같은 속성 값으로 필터링 할 수 있습니다. 4. 연령 및 이름 길이 조건을 동시에 충족하는 것과 같은 다중 조건 필터링 지원; 5. 동적 조건을 처리하고 필터 매개 변수를 기능으로 전달하여 유연한 필터링을 달성 할 수 있습니다. 6. 그것을 사용할 때는 빈 배열을 반환하지 않기 위해 부울 값을 반환하고 다른 방법을 결합하여 문자열 일치와 같은 복잡한 논리를 달성하십시오.

JavaScript에서 배열에 특정 값이 포함되어 있는지 확인하십시오. 가장 일반적인 방법은 부울 값을 반환하는 ()와 구문이 array.includes (valuetofind)입니다. 이전 환경과 호환 해야하는 경우 숫자. indexof (20)! == -1과 같은 indexof ()를 사용하십시오. 객체 또는 복잡한 데이터의 경우 user.some (user => user.id === 1)과 같은 심층 비교에 일부 () 메소드를 사용해야합니다.

비동기 함수의 오류를 처리하려면 시도/캐치를 사용하고 통화 체인에서 처리하고 .catch () 메소드를 사용한 후 처리되지 않은 반응 이벤트를 듣습니다. 1. 시도/캐치를 사용하여 오류를 잡는 오류는 명확한 구조와 함께 권장되는 방법이며 기다릴 수있는 예외를 처리 할 수 있습니다. 2. 통화 체인의 오류 처리는 중앙 집중식 로직 일 수 있으며, 이는 다단계 프로세스에 적합합니다. 3. Async 함수를 호출 한 후 .catch ()를 사용하여 약속 조합 시나리오에 적합합니다. 4. 처리되지 않은 거부를 마지막 방어선으로 기록하기 위해 처리되지 않은 주사 사건을 듣습니다. 위의 방법은 공동으로 비동기 오류가 올바르게 캡처되고 처리되도록 보장합니다.

Virtual Dom은 실제 DOM 업데이트를 최적화하는 프로그래밍 개념입니다. 메모리에서 실제 DOM에 해당하는 트리 구조를 만들면 실제 DOM의 빈번하고 직접 작동을 피합니다. 핵심 원칙은 다음과 같습니다. 1. 데이터가 변경 될 때 새로운 가상 DOM을 생성합니다. 2. 새 가상 Doms와 오래된 가상 Doms의 가장 작은 차이를 찾으십시오. 3. 재 배열 및 재로 그리기의 오버 헤드를 줄이기 위해 실제 DOM의 배치 업데이트. 또한 고유 한 안정 키를 사용하면 목록 비교 효율성을 향상시킬 수있는 반면, 일부 현대 프레임 워크는 가상 DOM을 대체하기 위해 다른 기술을 채택했습니다.

JavaScript의 범위는 변수의 접근성 범위를 결정하며, 이는 글로벌, 기능 및 블록 수준 범위로 나뉩니다. 컨텍스트는 이것의 방향을 결정하고 함수 호출 방법에 따라 다릅니다. 1. 스코프에는 글로벌 범위 (어디서나 액세스 가능), 함수 스코프 (함수 내에서만 유효 함) 및 블록 레벨 범위 ({} 내에서 유효 함)가 포함됩니다. 2. 실행 컨텍스트에는 가변 객체, 스코프 체인 및 이것의 값이 포함되어 있습니다. 이것은 일반 함수에서 글로벌 또는 정의되지 않은 것을 가리키며, 메소드 호출은 통화 객체를 가리키고 생성자는 새 객체를 가리키며 Call/Apply/Bind에 의해 명시 적으로 지정 될 수 있습니다. 3. 폐쇄는 외부 범위 변수에 액세스하고 기억하는 기능을 말합니다. 종종 캡슐화 및 캐시에 사용되지만

참고 : 1. 일반 함수를 사용하여 요소를 가리키십시오. 2. 동일한 함수를 사용하여 결합 할 때 참조하십시오. javaScript에서 ement. AddeventListener (EventType, HandlerFunction, 옵션)는 요소 바인딩 이벤트로 사용되며 다중 처리 함수를 지원하며이를 덮어 쓰지 않습니다. 예를 들어, btn.adeventListener ( 'click', function () {}); 이것은 일반 함수에서 요소 자체를 가리키고 화살표 함수는 외부 범위를 상속하므로 일반 함수는 관련 될 때 선택해야합니다. 제거 해야하는 경우
