我写了这个简单的Restful网络服务,并得到一个空白的回复。为什么?

时间:2016-05-02 06:58:56

标签: php web-services rest restful-architecture restful-url

我正在学习用PHP编写Restful webservice。所以我按照视频教程编写了以下基本Web服务。问题是当我尝试通过http://localhost/Test8/?name=c访问网络服务时(因为我的index.php目录位于Test8目录中),我得到一个空白页

但是当视频中的导师使用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

1 个答案:

答案 0 :(得分:3)

您的deliver_response()功能实际上并未将结果发送到浏览器。它只是将$response编码为JSON并将其存储在$json_response

尝试在该功能的末尾添加echo $json_response;

然后,访问您的网址:http://localhost/Test8/?name=Java