jQuery의 AJAX 를 사용한 서버측 PHP 간의 비동기 요청과 응답처리 예
jQuery 설정 및 테스트
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML Example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>여기를 클릭하세요
</body>
</html>
위의 방법보다 더 간단하게 jQuery 의 ready 함수를 실행하는 방법
<script>
$().ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
가장 간단한 jQuery ready 함수 호출 방법
$(function(){
$("p").click(function(){
$(this).hide();
});
});
jQuery의 AJAX 기능을 사용한 서버측(PHP)과의 비동기 통신
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$().ready(function(){
$("p").click(function(){
$(this).hide();
$.ajax(
{
url : 'server.php',
data : {name:'smith', phone:'010-9578-2154'},
dataType : 'json', /*html, text, json, xml, script*/
method : 'post',
success : function(res){
alert(res.name + ', '+res.phone);
$('p').show();
},
error : function(xhr, status, error){
alert(xhr.status); // 에러코드(404, 500 등)
alert(xhr.responseText); // html 포맷의 에러 메시지
alert(status); // 'error'
alert(error); // 'Not Found'
}
}
);
});
});
</script>
</head>
<body>
<p>AJAX Request Test
</body>
</html>
위의 요청에 응답하는 서버측 PHP 스크립트(server.php)
<?php
$name = $_REQUEST['name'];
$phone = $_REQUEST['phone'];
$arr['name'] = $name;
$arr['phone'] = $phone;
$json_str = json_encode($arr);
echo $json_str;
?>