【问题标题】:CakePHP 3.0: Response as jsonCakePHP 3.0:响应为 json
【发布时间】:2015-11-02 11:23:09
【问题描述】:

我正在创建一个 CakePHP 3.0 REST API。我关注了this instructions (routing in the book),并收到了 json 格式的回复。这是我的代码。

01 src/config/rout.php

Router::extensions('json');

02 src/controler/UsersController.php

  public function view($id = null) {
    $data = array('status' => 'o','status_message' => 'ok' );
    $this->set('data', $data);
    $this->set('_serialize', 'data');  
}

03 向该 URL 发送 post 请求

http://domain.com/users/view.json

输出:

{
    "status": "o",
    "status_message": "ok"
}

但我想在没有 .json 扩展名的情况下输出 json。提前谢谢你。

【问题讨论】:

  • 尝试使用Router::parseExtensions('json'); 而不是Router::extensions('json'); ?
  • 但是,3-0-migration-guide says Router::parseExtensions() 已被删除。请改用 Cake\Routing\Router::extensions()。必须在连接路由之前调用此方法。它不会修改现有路线。
  • @Maraboc 无论如何我都不想为我的 URL 添加扩展名。我想输出不带 .json 扩展名的 JSON 响应。
  • 你需要传递像Accept: application/json这样的标题,你会得到json格式的输出。

标签: php json cakephp url-routing cakephp-3.x


【解决方案1】:

我有同样的情况,但现在我找到了解决方案。现在我可以在没有 .json 的情况下放置请求 url,也可以获取 Json 数据作为响应。

在 App 控制器中添加将处理您的响应的网络响应。

使用 Cake\Network\Response;

之后你需要在数组中转换Json输入,所以把这个getJsonInput()函数放在你的AppController中并在initialize()中调用它

public function getJsonInput() {
        $data = file_get_contents("php://input");
        $this->data = (isset($data) && $data != '') ? json_decode($data, true) : array();
    }

现在在您的控制器中,您在$this->data 中拥有所有发布数据。因此您可以访问所有输入。 这是一个例子:

class UsersController extends AppController {

    public function index() {

        if ($this->request->is('post')) {
            //pr($this->data);    //here is your all inputs
           $this->message = 'success';
           $this->status = true;
        }
        $this->respond();
    }
}

现在,在函数结束时,您需要调用 respond(),它在 AppController 中定义

public function respond() {  
        $this->response->type('json');  // this will convert your response to json
        $this->response->body([
                    'status' => $this->status,
                    'code' => $this->code,
                    'responseData' => $this->responseData,
                    'message'=> $this->message,
                    'errors'=> $this->errors,
                ]);   // Set your response in body
        $this->response->send();  // It will send your response
        $this->response->stop();  // At the end stop the response
    }

AppController中的所有变量定义为

public $status = false;
public $message = '';
public $responseData = array();
public $code = 200;
public $errors = '';

还有一件事是:

Response.php (/vendor/cakephp/cakephp/src/Network/Response.php) 您需要在 586 处编辑一行 echo $content;echo json_encode($content);_sendContent() 函数中。

就是这样。现在您可以将请求网址设置为 domain_name/project_name/users/index.

【讨论】:

    【解决方案2】:

    如果有人还在寻找简单的 json 响应解决方案,这里是一个快速的解决方案:

    将此方法添加到您的 AppController.php

    public function jsonResponse($responseData = [], $responseStatusCode = 200) {
    
        Configure::write('debug', 0);
    
        $this->response->type('json');
        $this->response->statusCode($responseStatusCode);
        $this->response->body(json_encode($responseData));
        $this->response->send();
        $this->render(false,false);
    
    }
    

    你可以在任何简单的动作中使用它

    $data = ['status' => 'ok', 'foo' => 'bar'];
    $this->jsonResponse($data);
    

    还有一个例子

    $data = ['status' => 'failed', 'bar' => 'foo'];
    $this->jsonResponse($data, 404);
    

    希望有帮助:)

    【讨论】:

      【解决方案3】:

      使用proper HTTP accept headerAccept: application/json 请求您的数据,然后RequestHandler 应该接收它。

      HTTP 客户端使用 Accept 标头告诉服务器什么 他们会接受的内容类型。然后服务器会发回一个 响应,其中将包含一个 Content-Type 标头,告诉客户端 返回内容的实际内容类型是什么。

      但是,您可能已经注意到,HTTP 请求也可以包含 内容类型标头。为什么?好吧,考虑一下 POST 或 PUT 请求。 使用这些请求类型,客户端实际上是在发送一堆 作为请求的一部分向服务器发送数据,以及 Content-Type 标头 告诉服务器数据实际上是什么(从而确定如何 服务器会解析它)。

      特别是对于由 HTML 表单产生的典型 POST 请求 提交时,请求的 Content-Type 通常是 application/x-www-form-urlencoded 或 multipart/form-data。

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 1970-01-01
        • 2018-08-23
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多