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
'JavaScript' 카테고리의 다른 글
바닐라 JS : XMLHttpRequest(ajax) - Fetch API (0) | 2024.06.11 |
---|---|
js. content.indexOf()함수 (0) | 2023.12.12 |
JavaScript : PHP header()페이지 이동과 비슷한 JS 페이지 이동 location.href = "도메인"; (0) | 2023.04.13 |
JavaScript : <button> 클릭 시 페이지 이동 (0) | 2023.04.12 |
JavaScript : function back() 뒤 페이지로 넘어가기 (0) | 2023.04.11 |