我正在学习用PHP编写Restful Web服务。因此,我遵循了一个视频教程,并编写了以下基本的Web服务。问题是,当我尝试通过http://localhost/Test8/?name=c
(因为我的index.php
位于Test8
目录中)URL访问web服务时,我会得到一个空白页面。
但当视频中的导师使用http://localhost/rest/?name=c
访问时(因为他们的index.php
位于rest
目录中),他们在网页中获得了{"status":200, "status_message":"Book found", "data":348}
我错过了什么
index.php:
<?php
//Process client's request (via URL)
header("Content-Type:application/json");
if ( !empty($GET['name']) ) {
$name = $GET['name'];
$price = get_price($name);
if (empty($price)) {
//Book not found
deliver_response(200, 'Book not found!', NULL);
} else {
//Send the response with book price
deliver_response(200, 'Book found', $price);
}
} else {
//throw invalid request
deliver_response(400, "Invalid Request", NULL);
}
//API Functions
function get_price($bookRequested) {
$books = array(
'Java' => 999,
'C' => 348,
'PHP' =>500
);
foreach ($books as $book=>$price) {
if ($book == $bookRequested) {
return $price;
}
}
}
function deliver_response($status, $status_message, $data) {
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
}
?>
编辑:
刚刚检查了控制台。上面写着Failed to load resource: the server responded with a status of 400 (Invalid Request)
我更改了
if ( !empty($GET['name']) ) {
...
} else {
//throw invalid request
...
}
到
if ( !empty($GET['name']) ) {
echo '$GET["name"] is NOT empty';
...
} else {
echo '$GET["name"] IS empty';
//throw invalid request
...
}
并且浏览器打印$GET["name"] IS empty
您的deliver_response()
函数实际上并没有将结果发送到浏览器。它只是将$response
编码为JSON,并将其存储在$json_response
中。
尝试在该函数的末尾添加一个echo $json_response;
。
然后,访问您的URL:http://localhost/Test8/?name=Java