وباکا

آموزش تخصصی برنامه نویسی وب

آموزش REST API با پی اچ پی – 7# ساخت برنامه کلاینت REST API با زبان جاوااسکریپت

در این قسمت صفحه ای طراحی می کنیم و کدهایی به زبان جاوااسکریپت در آن قرار می دهیم که با درخواست از یک REST API ، لیستی از رکوردها را درخواست کرده و آنها را در یک جدول نمایش دهد.

برنامه REST API که در این مثال استفاده شده است در قسمت زیر توضیح داده شده است:

ساخت یک RESTful API ساده در ارتباط با بانک اطلاعاتی با پی اچ پی

برنامه REST API با کد زیر و با نام api2.php   را داشته باشید:

<?php
function response($status , $data=0 , $message="OK")
{
header("Content Type :application/json");
header("HTTP/1.1 $status");
$res['status'] = ($status==200)?1:0;
$res['data'] = $data;
$res['message']=$message;
$res=json_encode($res);
echo $res;
exit;
}
function Fields()
{
$conn = mysqli_connect("localhost","root","","amoozesh");
$res= mysqli_query($conn , "SELECT * FROM `fields`");
$list=[];
while($row=mysqli_fetch_assoc($res))
$list[]=$row;
return $list;
}
function Studs()
{
$conn = mysqli_connect("localhost","root","","amoozesh");
$res= mysqli_query($conn , "SELECT * FROM studs");
$list=[];
while($row=mysqli_fetch_assoc($res))
$list[]=$row;
return $list;
}
function StudsByFid($fid)
{
$conn = mysqli_connect("localhost","root","","amoozesh");
$res= mysqli_query($conn , "SELECT * FROM studs WHERE fid=$fid");
$list=[];
while($row=mysqli_fetch_assoc($res))
$list[]=$row;
return $list;
}
$query = file_get_contents("php://input");
parse_str($query , $params);
if( isset($params['method']) )
{
$method = strtolower($params['method']);
switch($method)
{
case "fields" : $m=Fields();
response(200 , $m);
break;
case "studs" : $m=Studs();
response(200 , $m);
break;
case "studsbyfid":$m=StudsByFid($params['fid']);
response(200 , $m);
break;
default: response(400 , 0 , "method not defined");
}
} else response(400 , 0 , "method not defined");
?>

کلاینت REST API با جاوااسکریپت

حالا صفحه HTML که به عنوان کلاینت REST API استفاده می شود دارای کد زیر است

<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">show studs</button>
</div>
<br>
<div id="div1"></div>
<script>
function toTable(data)
{
var str="<table border='1' width='700'>";
for(i=0; i<data.length;i++)
{
str +="<tr><td>" +data[i].sid
+"</td><td>"+data[i].name
+"</td><td>"+data[i].avgr
+"</td><td>"+data[i].fid
+"</td></tr>";
}
str+="</table>";
return str;
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
var res= JSON.parse(this.responseText);
var data=res.data;
document.getElementById("div1").innerHTML=toTable(data);
}
};
xhttp.open("POST", "api2.php", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("method=studs");
}
</script>
</body>
</html>

 

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *

فهرست مطالب