JSON PHP
JSON의 일반적인 용도는 웹 서버에서 데이터를 읽고 이를 웹 페이지에서 표시하는 것입니다。
이 장에서는 클라이언트와 PHP 서버 간에 JSON 데이터를 교환하는 방법에 대해 설명합니다。
PHP 파일
PHP는 JSON을 처리하는 내장 함수를 제공합니다。
PHP 함수를 사용하여 json_encode()
PHP에서의 객체는 JSON으로 변환될 수 있습니다:
PHP 파일
<?php $myObj->name = "Bill Gates"; $myObj->age = 62; $myObj->city = "Seattle"; $myJSON = json_encode($myObj); echo $myJSON; ?>
클라이언트 측 JavaScript
이는 클라이언트 측의 JavaScript로, AJAX 호출을 사용하여 예제 PHP 파일을 요청합니다:
실례
사용 JSON.parse()
결과를 JavaScript 객체로 변환합니다:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; }); }); xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send();
PHP 배열
PHP 함수 json_encode()
그 때, PHP의 배열도 JSON으로 변환됩니다:
PHP 파일
<?php $myArr = array("Bill Gates", "Steve Jobs", "Elon Musk"); $myJSON = json_encode($myArr); echo $myJSON; ?>
클라이언트 측 JavaScript
이는 클라이언트 측의 JavaScript로, AJAX 호출을 사용하여 예제 PHP 파일을 요청합니다:
실례
이를 사용하세요 JSON.parse()
결과를 JavaScript 배열로 변환합니다:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; }); }); xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send();
PHP 데이터베이스
PHP는 서버 측 프로그래밍 언어로, 데이터베이스 접근과 같은 서버에서만 실행할 수 있는 작업에 사용해야 합니다.
서버에 데이터베이스가 있고 고객, 제품, 공급자 데이터가 포함되어 있다고 생각해보세요.
이제, "고객" 테이블의前十条记录를 가져오기 위해 서버를 요청해야 합니다:
실례
이를 사용하세요 JSON.stringify()
JavaScript 객체를 JSON으로 변환하려면:
obj = { "table":"customers", "limit":10 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; }); }); xmlhttp.open("GET", "demo_json_db.php?x=" + dbParam, true); xmlhttp.send();
예시 설명:
- table 속성과 limit 속성을 포함한 객체를 정의합니다.
- 이 객체를 JSON 문자열로 변환하세요.
- JSON으로 매개변수를 포함한 이 PHP 파일에 요청을 보냅니다.
- 요청이 결과를 반환할 때까지 기다립니다(JSON으로).
- PHP 파일에서 받은 결과를 표시합니다.
PHP 파일을 확인하세요
PHP 파일
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
PHP 파일 설명:
- PHP 함수를 사용하여 요청을 객체로 변환하세요
json_decode()
. - 데이터를 요청한 데이터로 배열을 채우기 위해 데이터베이스에 접근하세요.
- 배열을 객체에 추가하여 사용하세요
json_encode()
JSON을 반환하는 함수.
결과를 순회합니다
PHP 파일에서 받은 결과를 JavaScript 객체로 변환하거나, 이 예제에서는 JavaScript 배열로 변환하세요:
실례
사용 JSON.parse()
JSON을 JavaScript 객체로 변환하세요:
... xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].name + "<br>"; }); document.getElementById("demo").innerHTML = txt; }); }); ...
PHP 메서드 = POST
서버로 데이터를 보내는 경우, 일반적으로 HTTP POST 메서드를 사용하는 것이 좋습니다.
POST 메서드를 사용하여 AJAX 요청을 보내려면, 해당 메서드와 올바른 헤더를 지정해야 합니다.
서버로 데이터를 보내는 경우, 일반적으로 HTTP POST 메서드를 사용하는 것이 좋습니다. .send();
메서드의 매개변수:
실례
obj = { "table":"customers", "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].name + "<br>"; }); document.getElementById("demo").innerHTML = txt; }); }); xmlhttp.open("POST", "demo_json_db.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam);
PHP 파일에서 유일하게 다른 점은 전송된 데이터를 가져오는 방법입니다.
PHP 파일
사용 $_POST
이대로 $_GET
:
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_POST["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>