簡體   English   中英

我寫了這個簡單的Restful網絡服務,並得到一個空白的回復。 為什么?

[英]I wrote this simple Restful web-service and am getting a blank response. Why?

我正在學習用PHP編寫Restful webservice。 所以我按照視頻教程編寫了以下基本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}網頁中的{"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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM