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

[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);

?>

 



분류 제목
Basic JS - Common Mistakes -
Basic JS - Performance -
Basic JS - Reserved Words -
Basic JS - Versions -
Basic JS - JSON (제이슨) - 데이터 전송 위한 가벼운 자료 형식.
Form JS - Forms - 폼양식 유효성 제어
Form JS - Forms API - 폼유효성
Object JS - Object - 객체개념(=객체의미=객체정의) ★ 3
Object JS - Object Property - 객체속성 ★
Object JS - Object Methods - 객체메서드 ★
Object JS - Object Accessors - 객체접근자 (Getter/Setter = 게러/세러 = 게터/세터… 2
Functions JS - Function Definition - 함수선언방법 + 함수호출방법 ★★★ (= 함수구문 + 함수특…
Functions JS - Function Parameter/argument - 함수 (매개변수/독립변수) ※ 변수 종류 ※ …
Functions JS - Function Invocation - 함수호출방법1 = (함수방식 + 메서드방식 + 함수생성자방…
Functions JS - call() 메서드 - 함수호출방법2 (= call메서드 = 콜메서드)
DOM JS - DOM (= 돔 = 문서객체모델) 정의
DOM JS - Method - 메서드 (= HTML 요소에 대한 수행 작업)
DOM JS - Document - 문서객체
DOM JS - Element Selector - 주요 요소선택자 (= 객체찾기) ※ JS외부링크호출 주의사항
DOM JS - HTML - 내용입력/내용변경/속성값변경(=속성값입력)
3/67
목록
찾아주셔서 감사합니다. Since 2012