• 회원가입
  • 로그인
  • 구글아이디로 로그인

[JSON] JS - JSON - PHP (= 서버연동 = DB연동)

주요 학습 내용

 

1.

  • JSON의 일반적인 용도는 웹 서버에서 데이터를 읽고 웹 페이지에 데이터 표시.
  • 이 장에서는 클라이언트와 PHP 서버간에 JSON 데이터를 교환하는 방법 설명

 

2.

  • json_encode() 함수 - PHP 형태를 JSON 형태로 변경 (※ 한글 경우 암호화 된 형태로 보임.)
  • JSON.parse() 함수 - JSON 형태를 JS 형태로 변경 (= 브라우저에 출력 가능한 형태로 변경. 한글도 정상 출력)

 

 

 


 1.

PHP 객체 →  JSON 객체 → JS 객체 

 

1-1.

json_encode() PHP 객체를 JSON 객체로 변환 (※ PHP 내장 JSON 처리함수)

 

test.php 내용 (※ php 객체를 json 객체 형태로 변환)

 

<?php

if (!isset($myObj)) 

    $myObj = new stdClass();

$myObj->site="Homzzang";

$myObj->domain="Homzzang.com";

$myObj->open=2012;


$myJSON = json_encode($myObj);

echo $myJSON;

?>

 

결과값:
{"site":"\ud648\uc9f1\ub2f7\ucef4","domain":"Homzzang.com","open":2012}

주의: 핑크색 코드 라인이 없으면 아래 에러 발생.

Warning: Creating default object from empty value in ~ 코드 시작라인

(예) 파란색코드 없으면 출력 X

 

<?php

$ip = $_SERVER['REMOTE_ADDR'];

if (!isset($details)) $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));

echo $details->ip;

?>


 

 

1-2.

JSON.parse() JSON 객체를 JS 객체로 변환

 

json.php 내용 (※ ajax 이용해 test.php 파일에서 json 형태로 정보 가져와 출력)

 

<p id="demo"></p>


<script>

var xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    myObj = JSON.parse(this.responseText);

    document.getElementById("demo").innerHTML = myObj.site; // 사이트 키 출력

  }

};

xmlhttp.open("GET", "test.php", true); // test.php에서 정보 가져오기

xmlhttp.send();

</script>

 

결과값: 홈짱닷컴

※ readyState == 4 :  통신 종료 (= 통신 완료)
※ status == 200 : 통신 성공

※ 관련글 https://homzzang.com/b/js-79

 

 

 

2.

 PHP 배열 →  JSON 배열 → JS 배열 

 

2-1.

json_encode() PHP 배열을 JSON 배열로 변환 (※ PHP 내장 JSON 처리함수)

 
test.php 내용 (※ php 배열을 json 배열 형태로 변형)

 

<?php

$myArr = array("홈짱닷컴", "Homzzang.com", 2012);

$myJSON = json_encode($myArr);

echo $myJSON;

?>

 

결과값:
["\ud648\uc9f1\ub2f7\ucef4","Homzzang.com",2012]

 

 

2-2.

JSON.parse() JSON 배열을 JS 배열로 변환

 

js.php 내용 (※ ajax 이용해 test.php 파일에서 json 정보 가져와 출력)

 

<p id="demo"></p>


<script>

var xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    myObj = JSON.parse(this.responseText);

    document.getElementById("demo").innerHTML = myObj[0]// 첫 번째 배열값 출력

  }

};

xmlhttp.open("GET", "test.php", true); // test.php에서 정보 가져오기

xmlhttp.send();

</script>

 

결과값: 홈짱닷컴

※ readyState == 4 :  통신 종료 (= 통신 완료)
※ status == 200 : 통신 성공

※ 관련글 https://homzzang.com/b/js-79

 

 

3-1.

 PHP DB :   JSON 형태를 GET 방식으로 데이터 주고 받기 

 

3-1-1.

브라우저에서 서버로 데이터 요청

 

/b.php 소스 (json 형태로 출력)

 

<script>

obj = {"limit":10 }; // ① JS 객체 정의

dbParam = JSON.stringify(obj); // ② JS객체를 JSON 형태로 변환

xmlhttp = new XMLHttpRequest(); 

xmlhttp.onreadystatechange = function() {

    if(this.readyState == 4 && this.status == 200) { // ⑤ 결과가 JSON으로 반환될 때까지 기다림.

        document.getElementById("demo").innerHTML = this.responseText; // ⑥ PHP 파일에서 받은 결과 표시

    }

};

xmlhttp.open("GET", "a.php?x=" + dbParam, true); // ③ JSON 문자열을 매개변수로 갖는 a.php 파일 

xmlhttp.send(); // ④ 위 php 파일로 요청 전송

</script>

<div id="demo"></div>

 

 

3-1-2.

서버에서 요청 데이터 처리 코드

 

/a.php 소스

<?php

$obj = json_decode($_GET["x"], false); // ① b.php에서 넘어온 JSON 요청을 PHP 객체로 변환

$conn = new mysqli("localhost", "root", "autoset", "mw7"); // ② DB 연결 (호스트,아이디,비번,DB명)

$stmt = $conn->prepare("SELECT mb_name FROM g5_member LIMIT ?"); 

$stmt->bind_param("i",$obj->limit); // ③ 요청 데이터로 ? 자리 채움.

$stmt->execute();

$result = $stmt->get_result();

$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp); // ④ PHP 객체를 JSON 객체로 반환

?>

 

※ 핑크색 부분은 본인 테스트 환경에 맞게 수정

※ 도움: 왕계란 님 https://sir.kr/qa/300471

 

 

3-2.

 PHP DB :   JSON으로 주고 받은 결과 출력 (for-in 반복문 이용)

 

a.php 파일에서 받은 결과를 JS 객체 또는 JS 배열로 변환해 출력. (예제에선 배열 이용)

 

위 b.php 파일 소스를 아래 소스로 교체

 

/b.php 소스 (이쁘게 가공한 형태로 출력)


<script>

var obj, dbParam, xmlhttp, myObj, x, txt = "";

obj = {"limit":10 };

dbParam = JSON.stringify(obj);

xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    myObj = JSON.parse(this.responseText);

    for (x in myObj) {

      txt += myObj[x].mb_name + "<br>";

    }

    document.getElementById("demo").innerHTML = txt;

  }

};

xmlhttp.open("GET", "a.php?x=" + dbParam, true);

xmlhttp.send();

</script>


<p id="demo"></p>

 

 

 

4.

 PHP DB :   JSON 형태를 POST 방식으로 데이터 주고 받기

 

서버에 데이터 보낼 때 HTTP POST 방식 사용하는 것이 보안 상 가장 좋음.

POST 방식 사용해 AJAX 요청 보내려면 메서드와 올바른 헤더 지정해야 함.

서버에 전송된 데이터는 이제 send() 메서드의 인수여야 함.

 

4-1. 

b.php 파일 (브라우저 측)

 

<p id="demo"></p>


<script>

var obj, dbParam, xmlhttp, myObj, x, txt = "";

obj = { "limit":10 };

dbParam = JSON.stringify(obj);

xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {

    myObj = JSON.parse(this.responseText);

    for (x in myObj) {

      txt += myObj[x].mb_name + "<br>";

    }

    document.getElementById("demo").innerHTML = txt;

  }

};

xmlhttp.open("POST", "a.php", true);

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xmlhttp.send("x=" + dbParam);

</script>

 

 

 

a.php (서버측)

 

<?php

header("Content-Type: application/json; charset=UTF-8");

$obj = json_decode($_POST["x"], false);


$conn = new mysqli("localhost", "root", "autoset", "mw7");

$stmt = $conn->prepare("SELECT mb_name FROM g5_member LIMIT ?");

$stmt->bind_param("i", $obj->limit);

$stmt->execute();

$result = $stmt->get_result();

$outp = $result->fetch_all(MYSQLI_ASSOC);


echo json_encode($outp);

?>

 


방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

분류 제목
JSON JS - JSON - Introduction (소개)
JSON JS - JSON - Syntax (구문) ★
JSON JS - JSON - JSON vs XML (언어비교)
JSON JS - JSON - Data Types (데이터타입)
JSON JS - JSON - Object (객체)
JSON JS - JSON - Array (배열)
JSON JS - JSON - JSON.parse() 함수 ★ - (JSON문자열 → JS객체) 변환. (= 웹서버와…
JSON JS - JSON - JSON.stringify() 함수 ★ - (JS객체 → JSON문자열) 변환. ※ P…
JSON JS - JSON - PHP (= 서버연동 = DB연동)
JSON JS - JSON - HTML (= 테이블 및 드롭다운 형태로 출력 + 출력개수선택)
JSON JS - JSON - JSONP (= script 이용한 서버연동)
목록
찾아주셔서 감사합니다. Since 2012