자바스크립트에서 setInterval() 을 이용하면 지정한 밀리세컨드 단위로 무언가를 실행할 수 있다.
이 함수에 ajax를 넣어서 1초에 한번 씩 실행되게 한다면 서버의 시간을 브라우저로 보낼 수 있다.
서버에서 할 일은 php의 date()함수와 time() 함수를 이용해서 실시간을 echo하면 된다. 이 예제에서는 util.php?mode=nowTime 링크에서 구현하였다.
util.php 의 코드 내용은 아래와 같다.
<?php
$mode = $_GET['mode'];
switch($mode){
case 'nowTime':
echo date("Y년 m월 d일 H:i:s",time());
break;
default:
break;
}
그리고 html과 javascript를 통해서 ajax를 구현한다.
$.get 함수를 이용하면 간단한 몇 줄로 ajax를 구현할 수 있다. 코드는 아래와 같다. 물론 헤더에 jquery를 import하는 것을 잊지 말자. 사소한 실수는 삽질과 함께 내면의 분노를 만든다.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<meta name='apple-mobile-web-app-capable' content='yes' />
<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />
<meta http-equiv='X-UA-Compatible' content='IE=edge, chrome=1' />
<meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no' />
<link rel='stylesheet' href='http://lib.inmu.net/jquery/jquery.mobile-1.4.5.min.css' />
<script src='http://lib.inmu.net/jquery/jquery_3_min.js'></script>
<script src='http://lib.inmu.net/jquery/jquery.mobile-1.4.5.min.js'></script>
<style>
body{
padding:1rem;
color:#717171;
font-size:.8rem
}
p,div{
padding:.2rem;
border-bottom:1px solid #717171;
}
#ajax_001{
font-size:4rem;
color:#717171;
}
</style>
<script>
$(window).ready(function(){
setInterval(function(){
$.get( "util.php", { mode: "nowTime" } )
.done(function( data ) {
$("#ajax_001").html(data );
});
},1000);
});
</script>
<title>1712 첫번째 연습</title>
</head>
<body>
<p>아래에 서버의 시간을 보여준다.</p>
<div id="ajax_001"></div>
</body>
</html>
이제 브라우저에서 서버의 시간을 1초에 한 번씩 전송 받을 수 있게 되었다.
아래에 예제 페이지를 볼 수 있는 링크가 있다.