JavaScript

바닐라 JS : XMLHttpRequest(ajax) - 모듈화

제주도 조랑말 2024. 6. 11. 14:46
728x90

1. index.php에서는 POST, GET, URL을 자신이 원하는 것에맞게 사용

2. ajax.js에서 HTML, JSON, XML에 맞게 사용 3번도 같이 수정 ex) json_encode

 

index.php

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>동적 검색 예제</title>
<script src="/js/ajax.js"></script>
</head>
<body>

    <input type="text" id="vl" name="vl"/>
    <button onclick="submit()"> 전송 </button>
 

    <script>
        const submit = () => {
            const sender = new DataSender('/test1.php', 'GET');
            sender.send(document.getElementById('vl').value);
        }
    </script>
   
</body>
</html>

 

 

ajax.js

class DataSender {
    constructor(url, methodVl) {
        this.url = url;
        this.methodVl = methodVl;
    }

    send(vlValue) {
        const xhr = new XMLHttpRequest();
        const sendData = 'vl=' + encodeURIComponent(vlValue);


        if(this.methodVl == 'GET'){

           

                const urlWithParams = `${this.url}?${sendData}`;
                xhr.open('GET', urlWithParams, true);
               
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        alert('서버로 GET 성공적으로 전송되었습니다!');
                        console.log(xhr.responseText);
                    }
                };
               
                xhr.onerror = () => {
                    alert('데이터 전송 중 오류가 발생했습니다!');
                };

                xhr.send();
        }else if(this.methodVl == 'POST'){
                xhr.open('POST', this.url, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        alert('서버로 POST 성공적으로 전송되었습니다!');
                        console.log(xhr.responseText);
                    }
                };
           
                xhr.onerror = () => {
                    alert('데이터 전송 중 오류가 발생했습니다!');
                };
           
                xhr.send(sendData);
        }
    }
}

 

 

test1.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $vl = $_POST['vl'];
        echo $vl;
}else if($_SERVER['REQUEST_METHOD'] == 'GET') {
    $vl = $_GET['vl'];
    echo $vl;
}


?>
728x90