


Bereksperimen dengan AJAX dan API: Panduan Komprehensif untuk Pemula
1. Pengenalan kepada AJAX dan API
Apakah AJAX?
AJAX bermaksud JavaScript dan XML Tak Segerak. Ia adalah teknik yang digunakan dalam pembangunan web untuk mencipta halaman web yang dinamik dan interaktif tanpa perlu memuatkan semula keseluruhan halaman. Dengan AJAX, anda boleh meminta data daripada pelayan dan mengemas kini bahagian halaman web secara tidak segerak, bermakna pengguna boleh terus berinteraksi dengan halaman semasa permintaan sedang diproses di latar belakang.
Apakah API?
Satu API (Antara Muka Pengaturcaraan Aplikasi) ialah satu set peraturan dan takrifan yang membolehkan aplikasi perisian yang berbeza berkomunikasi antara satu sama lain. Dalam konteks pembangunan web, API sering digunakan untuk berinteraksi dengan pelayan web, mendapatkan semula data dan menghantar data. API boleh menjadi awam (tersedia untuk digunakan oleh sesiapa sahaja) atau peribadi (terhad kepada pengguna atau aplikasi tertentu).
Mengapa Menggunakan AJAX dan API Bersama?
Apabila anda menggunakan AJAX dan API bersama-sama, anda mendayakan aplikasi web anda untuk mengambil, menghantar dan mengemas kini data secara dinamik. Gabungan ini membolehkan anda membina aplikasi web yang kaya, responsif dan interaktif yang memberikan pengalaman pengguna yang lancar tanpa muat semula halaman yang berterusan.
Aplikasi Dunia Sebenar AJAX dan API
- Suapan Media Sosial: Platform seperti Twitter dan Facebook menggunakan AJAX untuk memuatkan siaran dan ulasan baharu secara dinamik tanpa memuatkan semula halaman.
- Aplikasi Cuaca: Apl cuaca mengambil data cuaca masa nyata daripada API untuk memaparkan keadaan dan ramalan semasa.
- Tapak Web E-dagang: Kedai dalam talian menggunakan AJAX untuk ciri seperti menapis produk, mengemas kini troli beli-belah dan memproses pesanan tanpa muat semula halaman.
- Perkhidmatan Peta dan Lokasi: Perkhidmatan seperti Peta Google menggunakan AJAX untuk memuatkan jubin peta dan data lokasi secara dinamik berdasarkan input pengguna.
2. Bermula dengan AJAX
Memahami JavaScript dan XML Asynchronous (AJAX)
AJAX bukan satu teknologi tetapi gabungan pelbagai teknologi yang berfungsi bersama:
- JavaScript: Digunakan untuk mengendalikan interaksi pengguna dan membuat permintaan tak segerak.
- XML/JSON: Format untuk bertukar-tukar data antara klien dan pelayan. JSON (JavaScript Object Notation) lebih biasa digunakan hari ini.
- HTML/CSS: Digunakan untuk menstruktur dan menggayakan kandungan halaman web.
- DOM (Model Objek Dokumen): Mewakili struktur halaman web dan membenarkan JavaScript berinteraksi dengannya.
Konsep Asas AJAX
- Komunikasi Asynchronous: AJAX membenarkan halaman web menghantar dan menerima data daripada pelayan secara tidak segerak, bermakna penyemak imbas tidak perlu menunggu respons pelayan sebelum meneruskan tugas lain.
- Kemas Kini Halaman Separa: Daripada memuatkan semula keseluruhan halaman, AJAX boleh mengemas kini bahagian tertentu halaman web, meningkatkan prestasi dan pengalaman pengguna.
- Komunikasi Pelayan-Pelanggan: AJAX membolehkan JavaScript bahagian pelanggan berkomunikasi dengan API bahagian pelayan untuk mengambil atau menghantar data.
Bagaimana AJAX Berfungsi
- Tindakan Pengguna: Pengguna mencetuskan acara, seperti mengklik butang atau memasukkan teks dalam borang.
- Pelaksanaan JavaScript: JavaScript menangkap acara dan mencipta objek XMLHttpRequest.
- Permintaan Pelayan: Objek XMLHttpRequest menghantar permintaan kepada pelayan.
- Pemprosesan Pelayan: Pelayan memproses permintaan dan menghantar balasan kembali kepada klien.
- Kemas Kini Pelanggan: JavaScript menerima respons pelayan dan mengemas kini halaman web secara dinamik.
Permintaan AJAX pertama dengan JavaScript
Untuk menunjukkan asas AJAX, mari buat halaman HTML mudah dan gunakan JavaScript untuk menghantar permintaan AJAX ke pelayan.
Panduan Langkah demi Langkah:
- Buat Fail 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.Buat Fail 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.Uji Permintaan 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 | پیمان عابدین پور
Atas ialah kandungan terperinci Bereksperimen dengan AJAX dan API: Panduan Komprehensif untuk Pemula. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Terdapat tiga cara biasa untuk memulakan permintaan HTTP dalam node.js: Gunakan modul terbina dalam, axios, dan nod-fetch. 1. Gunakan modul HTTP/HTTPS terbina dalam tanpa kebergantungan, yang sesuai untuk senario asas, tetapi memerlukan pemprosesan manual jahitan data dan pemantauan ralat, seperti menggunakan https.get () untuk mendapatkan data atau menghantar permintaan pos melalui .write (); 2.AXIOS adalah perpustakaan pihak ketiga berdasarkan janji. Ia mempunyai sintaks ringkas dan fungsi yang kuat, menyokong async/menunggu, penukaran JSON automatik, pemintas, dan lain -lain. Adalah disyorkan untuk memudahkan operasi permintaan tak segerak; 3.Node-Fetch menyediakan gaya yang serupa dengan pengambilan penyemak imbas, berdasarkan janji dan sintaks mudah

Jenis data JavaScript dibahagikan kepada jenis primitif dan jenis rujukan. Jenis primitif termasuk rentetan, nombor, boolean, null, undefined, dan simbol. Nilai -nilai tidak berubah dan salinan disalin apabila memberikan nilai, jadi mereka tidak mempengaruhi satu sama lain; Jenis rujukan seperti objek, tatasusunan dan fungsi menyimpan alamat memori, dan pembolehubah menunjuk objek yang sama akan mempengaruhi satu sama lain. Typeof dan Instanceof boleh digunakan untuk menentukan jenis, tetapi memberi perhatian kepada isu -isu sejarah TypeOfNull. Memahami kedua -dua jenis perbezaan ini dapat membantu menulis kod yang lebih stabil dan boleh dipercayai.

Kaedah penapis () dalam JavaScript digunakan untuk membuat array baru yang mengandungi semua elemen ujian lulus. 1.filter () tidak mengubah suai array asal, tetapi mengembalikan array baru yang memenuhi unsur -unsur bersyarat; 2. Sintaks asas adalah array.filter ((elemen) => {returnCondition;}); 3. Arahan objek boleh ditapis dengan nilai atribut, seperti penapisan pengguna yang lebih tua dari 30; 4. Menyokong penapisan pelbagai syarat, seperti memenuhi syarat umur dan nama panjang pada masa yang sama; 5. Boleh mengendalikan keadaan dinamik dan lulus parameter penapis ke dalam fungsi untuk mencapai penapisan fleksibel; 6. Apabila menggunakannya, berhati -hati untuk mengembalikan nilai Boolean untuk mengelakkan kembali tatasusunan kosong, dan menggabungkan kaedah lain untuk mencapai logik kompleks seperti padanan rentetan.

Dalam JavaScript, periksa sama ada array mengandungi nilai tertentu. Kaedah yang paling biasa termasuk (), yang mengembalikan nilai boolean dan sintaks adalah array. termasuk (valueTofind), contohnya buah -buahan. termasuk ('pisang') kembali benar; Sekiranya perlu bersesuaian dengan persekitaran lama, gunakan indexof (), seperti nombor.indexof (20)! ==-1 pulangan benar; Untuk objek atau data yang kompleks, beberapa () kaedah harus digunakan untuk perbandingan mendalam, seperti users.some (user => user.id === 1) pulangan benar.

Untuk mengendalikan kesilapan dalam fungsi asynchronous, gunakan cuba/menangkap, mengendalikannya dalam rantaian panggilan, gunakan kaedah .catch (), dan dengar peristiwa yang tidak dimanfaatkan. 1. Gunakan cuba/menangkap untuk menangkap kesilapan adalah kaedah yang disyorkan, dengan struktur yang jelas dan boleh mengendalikan pengecualian dalam menanti; 2. Kesilapan mengendalikan dalam rantaian panggilan boleh menjadi logik berpusat, yang sesuai untuk proses pelbagai langkah; 3. Gunakan .catch () untuk menangkap kesilapan selepas memanggil fungsi async, yang sesuai untuk senario kombinasi janji; 4. Dengarkan peristiwa yang tidak diingini untuk merakam penolakan yang tidak dialami sebagai barisan pertahanan terakhir; Kaedah di atas bersama -sama memastikan bahawa kesilapan asynchronous ditangkap dengan betul dan diproses.

Kunci untuk menangani isu zon waktu JavaScript adalah memilih kaedah yang betul. 1. Apabila menggunakan objek tarikh asli, disarankan untuk menyimpan dan memindahkan masa UTC dan menukarnya ke zon waktu tempatan pengguna ketika memaparkan; 2. Untuk operasi zon waktu yang kompleks, momen-TIMEZONE boleh digunakan, yang menyokong pangkalan data zon waktu IANA dan menyediakan fungsi pemformatan dan penukaran yang mudah; 3. Jika anda perlu melokalkan masa paparan dan tidak mahu memperkenalkan perpustakaan pihak ketiga, anda boleh menggunakan intl.dateTimeFormat; 4. Adalah disyorkan untuk penyelesaian ringan hari ini.js dan zon waktu dan pemalam UTC, yang mempunyai API ringkas, prestasi yang baik dan menyokong penukaran zon waktu.

Maya DOM adalah konsep pengaturcaraan yang mengoptimumkan kemas kini DOM sebenar. Dengan mewujudkan struktur pokok yang sepadan dengan DOM sebenar dalam ingatan, ia mengelakkan operasi DOM yang kerap dan langsung. Prinsip terasnya ialah: 1. Menjana DOM maya baru apabila data berubah; 2. Cari perbezaan terkecil antara dom maya baru dan lama; 3. Kemas kini batch DOM sebenar untuk mengurangkan overhead penyusunan semula dan redrawing. Di samping itu, dengan menggunakan kunci stabil yang unik dapat meningkatkan kecekapan perbandingan senarai, sementara beberapa rangka kerja moden telah mengadopsi teknologi lain untuk menggantikan DOM maya.

Fungsionalprogramminginjavascriptemphasizesclean, predicableCodeThroughcoreconcepts.1.purefunctionsconsistentlyreturnthesameOutputWithoutSideFefects, IntervingTestabilityandPredictability.2.immutabilityavoidsdatamodificycreatingnewdatacies
