Végpont | ||
---|---|---|
products | GET | az összes terméket adja |
<?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); read_data(); function read_data() { $data = [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ]; $res = json_encode( $data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ); echo $res; }
A tömb egyszerűsített verzióját használtuk PHP-ban. Így is írhatjuk:
$data = array( array( "id"=>1, "name"=>"vaj", "price"=>1.8 ), array( "id"=>2, "name"=>"kenyér", "price"=>0.8 ), array( "id"=>3, "name"=>"tej", "price"=>0.9 ) );
A product tulajdonság megadása:
$data = [ "products" => [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ] ];
Ezek után csak a termékekre így hivatkozunk:
$res = json_encode( $data['products'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
$data = [ "products" => [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ], "customers" => [ ["id"=>1, "name"=>"Penge Béla", "city"=>"Szeged"], ["id"=>2, "name"=>"Ezres Irén", "city"=>"Szeged"], ["id"=>3, "name"=>"Látó Ervin", "city"=>"Szeged"], ] ];
[ { "id": 1, "name": "vaj", "price": 2 }, { "id": 2, "name": "kifli", "price": 0.7 }, { "id": 3, "name": "vaj", "price": 2 } ]
<?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); read_data(); function read_data() { $page = file_get_contents('../database.json'); echo $page; }
{ "products": [ { "id": 1, "name": "vaj", "price": 2 }, { "id": 2, "name": "kifli", "price": 0.7 }, { "id": 3, "name": "vaj", "price": 2 } ] }
<?php header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); read_data(); function read_data() { $page = file_get_contents('../database.json'); $obj = json_decode($page); $res = json_encode( $obj->{'products'}, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ); echo $res; }
var url = 'http://localhost:3000/api/products'; fetch(url) .then(res => res.json()) .then(res => { console.log(res ); });
Táblázat a HTML oldalon.
<table class="table table-striped"> <thead> <tr> <th>#</th> <th>Név</th> <th>Ár</th> </tr> </thead> <tbody id="tableBody"> </tbody> </table>
const tableBody = document.querySelector('#tableBody'); var url = 'http://localhost:3000/api/products'; fetch(url) .then(res => res.json()) .then(res => { res.forEach(prod => { console.log(prod.name); let tr = document.createElement('tr'); let tdId = document.createElement('td'); let tdName = document.createElement('td'); let tdPrice = document.createElement('td'); tableBody.appendChild(tr); tr.appendChild(tdId); tr.appendChild(tdName); tr.appendChild(tdPrice); tdId.textContent = prod.id; tdName.textContent = prod.name; tdPrice.textContent = prod.price; }); });