회원로그인
[jQuery.$ajax]mysql + php 서버에서 json 데이터 얻어오기
10년 전
webapp, hybrid 프로젝트에 있어 가장 많이 쓰이는 기법인데 많은 자료가 없는 듯 해, 기본적인 예제를 통해 방법을 익힐 수 있도록 포스팅한다.
다양한 방법을 통해 db의 자료를 json형식으로 얻을 수 있겟지만, 가장 쉽게 구현할 수 있는 PHP JSON 라이브러리를 활용한 방법을 소개한다.
PHP JSON 라이브러리는 http://pear.php.net/package/Services_JSON/download/ 에서 다운로드 가능하다. 다운로드한 라이브러리(JSON.php)는 JSON데이터를 내려줄 서버에 등록하고, 코드 작성을 시작하겠다.
<?php
require('JSON.php'); // 서버에 등록한 라이브러리
try{
$connection = mysql_connect("localhost","아이디","비밀번호") or die ("Could not connect: " . mysql_error());
mysql_query("SET NAMES utf8", $connection);
mysql_select_db("DB명", $connection);
$sql = "SELECT * FROM 테이블";
$sth = mysql_query($sql) or die ("Could not connect: " . mysql_error());
//JSON객체생성
$json = new Services_JSON();
$rows = array();
while($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
$output = $json->encode($rows);
echo $output;
mysql_close($connection);
}catch(Exception $e){
//로그 기록
echo $e->getMessage();
}
?>
이제 서버에서 JSON 데이터를 내려줄 준비는 끝났다.
다음으로 서버에 JSON 데이터를 요청하고 받은 결과를 뿌려주는 화면 영역 코드 작성을 해보자.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>json데이터 사용하기</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="bodySwrap">
</div><!-- //bodySwrap -->
<script>
$.ajax({
type:'POST',
url:'작성한 서버 URL',
dataType:'json',
timeout: 10000,
success: function(data){
alert(data[0].subject);
alert(data.length);
},
error: function(request, textStatus, errorThrown){
//에러내용확인
alert('error: ' + textStatus);
},
});
</script>
</body>
</html>
위와 같이 작성이 되었다면, 브라우저에서 화면을 열어보자.
화면을 실행하면, DB에서 출력된 JSON의 첫번째 데이터의 subject필드 팝업 출력 후 JSON데이터의 길이 팝업이 출력될 것이다.
위와 같은 기본 구조를 활용하여, 다양한 방식으로 구현 가능할 것이다.
추천 : 485
추천
목록