[英]I wrote this simple Restful web-service and am getting a blank response. Why?
I am learning to write a Restful webservice in PHP. 我正在学习用PHP编写Restful webservice。 So I followed a video tutorial and wrote the following basic webservice.
所以我按照视频教程编写了以下基本Web服务。 The problem is that when I tried to access the web service via
http://localhost/Test8/?name=c
(because my index.php
is located in Test8
directory) URL, I get a blank page . 问题是,当我尝试通过
http://localhost/Test8/?name=c
(因为我的index.php
位于Test8
目录中)URL访问Web服务时, 我得到一个空白页面 。
But when the tutor in the video accessed it using http://localhost/rest/?name=c
(because their index.php
located in rest
directory), they got {"status":200, "status_message":"Book found", "data":348}
in the webpage. 但是当视频中的导师使用
http://localhost/rest/?name=c
(因为他们的index.php
位于rest
目录中)访问它时, 他们得到{"status":200, "status_message":"Book found", "data":348}
网页中的{"status":200, "status_message":"Book found", "data":348}
。
What did I miss? 我错过了什么?
index.php: 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);
}
?>
EDIT: 编辑:
Just checked the console. 刚刚检查了控制台。 It says
Failed to load resource: the server responded with a status of 400 (Invalid Request)
... 它说
Failed to load resource: the server responded with a status of 400 (Invalid Request)
...
I changed 我变了
if ( !empty($GET['name']) ) {
...
} else {
//throw invalid request
...
}
to 至
if ( !empty($GET['name']) ) {
echo '$GET["name"] is NOT empty';
...
} else {
echo '$GET["name"] IS empty';
//throw invalid request
...
}
and the browser prints $GET["name"] IS empty
. 并且浏览器打印
$GET["name"] IS empty
。
your deliver_response()
function doesn't actually send the result to the browser. 您的
deliver_response()
函数实际上并不将结果发送到浏览器。 It just encodes the $response
as JSON and stores it in $json_response
. 它只是将
$response
编码为JSON并将其存储在$json_response
。
Try adding an echo $json_response;
尝试添加
echo $json_response;
to the end of that function. 到那个功能的结尾。
And then, access your URL: http://localhost/Test8/?name=Java 然后,访问您的URL: http:// localhost / Test8 /?name = Java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.