티스토리 뷰
Of course! AJAX (Asynchronous JavaScript and XML) is a technique for creating dynamic web pages that update content without requiring a page reload. It allows you to make HTTP requests from JavaScript and handle the response without reloading the page.
Here are the basic steps for using AJAX:
- Create an XMLHttpRequest object: To make an AJAX request, you first need to create an instance of the XMLHttpRequest object. This object is built into most modern web browsers and allows you to make HTTP requests from JavaScript.
- Open the HTTP request: Once you have created an instance of the XMLHttpRequest object, you need to open the HTTP request. This involves specifying the HTTP method (e.g. GET or POST) and the URL of the server you want to send the request to.
- Send the request: After opening the HTTP request, you can send it to the server using the send() method of the XMLHttpRequest object. This method takes an optional parameter containing any data you want to send to the server (e.g. form data).
- Handle the response: Once the server has processed the request, it will send a response back to the browser. You can handle this response using the onreadystatechange event of the XMLHttpRequest object. When the readyState property of the object changes (indicating that the response has been received), you can access the response data using the responseText or responseXML properties.
Here's an example of how to use AJAX to fetch data from a server and update a web page without reloading it:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX Example</title>
<script>
function fetchData() {
// create an XMLHttpRequest object
var xhttp = new XMLHttpRequest();
// define a callback function to handle the response
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// update the page with the response data
document.getElementById("data").innerHTML = this.responseText;
}
};
// open the HTTP request
xhttp.open("GET", "https://example.com/data", true);
// send the request
xhttp.send();
}
</script>
</head>
<body>
<button onclick="fetchData()">Fetch Data</button>
<div id="data"></div>
</body>
</html>
In this example, the fetchData() function is called when the user clicks the "Fetch Data" button. This function creates an instance of the XMLHttpRequest object, sets the onreadystatechange event to a callback function that updates the page with the response data, opens a GET request to the URL "https://example.com/data", and sends the request to the server. When the response is received, the callback function updates the data div with the response text using the innerHTML property.
'개발' 카테고리의 다른 글
| GraphQL에 대해서 (0) | 2023.03.07 |
|---|---|
| React 간단예제 (0) | 2023.03.06 |
| [C#] Windows 프로그램이 실행중인지 체크 (0) | 2023.03.03 |
| DotNetty 빌드하는 법 (0) | 2023.02.28 |
| How does Grandmaster synchronize and train clocks from GPS/GNSS ? (0) | 2023.02.27 |
- Total
- Today
- Yesterday