코딩 스쿨 JavaScript

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP

JavaScript AJAX Examples

JavaScript AJAX Examples: 다양한 AJAX 요청 구현하기

AJAX (Asynchronous JavaScript and XML)는 웹 애플리케이션에서 비동기적으로 서버와 통신하는 데 유용한 기술입니다. 이 가이드는 다양한 AJAX 요청의 예제를 통해 AJAX를 사용하는 방법을 설명합니다.


1. 기본 AJAX 요청 예제

이 예제에서는 XMLHttpRequest 객체를 사용하여 서버에 데이터를 요청하고, 응답을 처리하는 기본적인 AJAX 요청을 구현합니다.

1.1. HTML 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic AJAX Example</title>
</head>
<body>
    <h1>Basic AJAX Example</h1>
    <button id="loadData">Load Data</button>
    <pre id="result"></pre>

    <script>
        document.getElementById('loadData').addEventListener('click', function() {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'data.json', true); // JSON 파일 요청

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    const data = JSON.parse(xhr.responseText); // JSON 응답 파싱
                    document.getElementById('result').textContent = JSON.stringify(data, null, 2); // 결과 출력
                } else {
                    console.error('Error:', xhr.statusText); // 오류 처리
                }
            };

            xhr.onerror = function() {
                console.error('Request failed'); // 요청 실패 처리
            };

            xhr.send(); // 요청 전송
        });
    </script>
</body>
</html>

  • 이 코드는 data.json 파일을 요청하고, 성공적으로 응답을 받으면 데이터를 출력합니다.

2. AJAX POST 요청 예제

사용자가 입력한 데이터를 서버로 POST 요청으로 전송하는 예제를 구현합니다.

2.1. HTML 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX POST Example</title>
</head>
<body>
    <h1>AJAX POST Example</h1>
    <form id="userForm">
        <input type="text" id="name" placeholder="Enter your name" required>
        <input type="number" id="age" placeholder="Enter your age" required>
        <button type="submit">Submit</button>
    </form>
    <pre id="response"></pre>

    <script>
        document.getElementById('userForm').addEventListener('submit', function(event) {
            event.preventDefault(); // 기본 제출 동작 방지

            const name = document.getElementById('name').value;
            const age = document.getElementById('age').value;

            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'submit.php', true); // PHP 스크립트 요청
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 요청 헤더 설정

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    document.getElementById('response').textContent = xhr.responseText; // 서버 응답 표시
                } else {
                    console.error('Error:', xhr.statusText); // 오류 처리
                }
            };

            xhr.send(`name=${encodeURIComponent(name)}&age=${encodeURIComponent(age)}`); // POST 데이터 전송
        });
    </script>
</body>
</html>

  • 이 코드는 사용자가 입력한 이름과 나이를 submit.php로 POST 요청하여 서버에서 처리한 후 응답을 표시합니다.

3. AJAX를 사용한 실시간 검색 예제

사용자가 입력하는 대로 실시간으로 서버에서 검색 결과를 가져오는 예제를 구현합니다.

3.1. HTML 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-time Search Example</title>
</head>
<body>
    <h1>Real-time Search Example</h1>
    <input type="text" id="search" placeholder="Search...">
    <div id="results"></div>

    <script>
        document.getElementById('search').addEventListener('input', function() {
            const query = this.value;

            const xhr = new XMLHttpRequest();
            xhr.open('GET', `search.php?q=${encodeURIComponent(query)}`, true); // PHP 스크립트 요청

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    document.getElementById('results').innerHTML = xhr.responseText; // 결과 표시
                } else {
                    console.error('Error:', xhr.statusText); // 오류 처리
                }
            };

            xhr.send(); // 요청 전송
        });
    </script>
</body>
</html>

  • 이 코드는 사용자가 입력할 때마다 search.php로 AJAX 요청을 보내고, 검색 결과를 실시간으로 표시합니다.

4. AJAX로 데이터 시각화하기

AJAX를 사용하여 외부 API에서 데이터를 가져오고 이를 차트로 시각화하는 예제를 구현합니다.

4.1. HTML 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Visualization Example</title>
    <script src="<https://cdn.jsdelivr.net/npm/chart.js>"></script>
</head>
<body>
    <h1>Data Visualization Example</h1>
    <canvas id="myChart"></canvas>

    <script>
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '<https://api.example.com/data>', true); // 외부 API 요청

        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText); // JSON 응답 파싱
                const ctx = document.getElementById('myChart').getContext('2d');
                const myChart = new Chart(ctx, {
                    type: 'bar', // 차트 유형
                    data: {
                        labels: data.labels, // X축 레이블
                        datasets: [{
                            label: 'Sample Data',
                            data: data.values, // Y축 값
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            } else {
                console.error('Error:', xhr.statusText); // 오류 처리
            }
        };

        xhr.send(); // 요청 전송
    </script>
</body>
</html>

  • 이 코드는 외부 API에서 데이터를 가져와 Chart.js를 사용하여 바 차트로 시각화합니다.

5. AJAX를 사용한 사용자 등록 및 데이터 전송 예제

사용자가 입력한 정보를 서버에 등록하는 예제를 구현합니다.

5.1. HTML 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Registration Example</title>
</head>
<body>
    <h1>User Registration</h1>
    <form id="registrationForm">
        <input type="text" id="username" placeholder="Username" required>
        <input type="email" id="email" placeholder="Email" required>
        <button type="submit">Register</button>
    </form>
    <pre id="response"></pre>

    <script>
        document.getElementById('registrationForm').addEventListener('submit', function(event) {
            event.preventDefault(); // 기본 제출 동작 방지

            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;

            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'register.php', true); // PHP 스크립트 요청
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    document.getElementById('response').textContent = xhr.responseText; // 서버 응답 표시
                } else {
                    console.error('Error:', xhr.statusText); // 오류 처리
                }
            };

            xhr.send(`username=${encodeURIComponent(username)}&email=${encodeURIComponent(email)}`); // 데이터 전송
        });
    </script>
</body>
</html>

  • 이 코드는 사용자가 입력한 사용자 이름과 이메일을 register.php로 POST 요청하여 서버에서 처리한 후 응답을 표시합니다.

6. 요약

JavaScript AJAX Examples는 웹 애플리케이션

의 성능과 사용자 경험을 크게 향상시킬 수 있는 기술입니다. AJAX를 활용하여 비동기적으로 데이터를 요청하고 처리함으로써 더 동적이고 반응성이 뛰어난 사용자 인터페이스를 구현할 수 있습니다.

  • 기본 AJAX 요청: JSON 파일 요청 및 처리.
  • POST 요청: 사용자 데이터를 서버로 전송.
  • 실시간 검색: 사용자의 입력에 따라 서버에서 검색 결과를 실시간으로 업데이트.
  • 데이터 시각화: 외부 API에서 데이터를 가져와 차트로 시각화.
  • 사용자 등록: 입력한 사용자 정보를 서버에 등록하는 기능.

JavaScript의 AJAX를 활용하여 사용자 경험을 개선하고, 더 나은 웹 애플리케이션을 개발할 수 있습니다.


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com