【问题标题】:I wrote this simple Restful web-service and am getting a blank response. Why?我编写了这个简单的 Restful Web 服务,但得到了空白响应。为什么?
【发布时间】:2016-05-02 06:58:55
【问题描述】:

我正在学习用 PHP 编写一个 Restful 网络服务。所以我按照视频教程编写了以下基本 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

【问题讨论】:

  • 我看到您的代码没有使用 json_encode 将 PHP 数组更改为 json。也许值得尝试添加 json_encode($price)。就个人而言,我从不使用交付响应,所以我不知道您是否需要转换数组。通常我只是回显 json 编码的数组。对我来说更简单。
  • 它是 $_GET 而不是 $GET
  • @Bharata 谢谢。请查看我的问题中的编辑。

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


【解决方案1】:

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

尝试将echo $json_response; 添加到该函数的末尾。

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

【讨论】:

  • 谢谢。你能看看我的问题中的编辑吗? $GET 为空。 =s
  • 是的,我只是添加了关于 $_GET 而不是 $GET 的评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
相关资源
最近更新 更多