CakePHP 3.0:响应为json

May*_*ama 2 php json cakephp url-routing cakephp-3.x

我正在创建一个CakePHP 3.0 REST API.我按照这个说明(书中的路由)并在json中收到了回复.这是我的代码.

01 src/config/rout.php

Router::extensions('json');
Run Code Online (Sandbox Code Playgroud)

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');  
}
Run Code Online (Sandbox Code Playgroud)

03发送一个帖子请求到这个URL

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

输出:

{
    "status": "o",
    "status_message": "ok"
}
Run Code Online (Sandbox Code Playgroud)

但是我想把json放在没有.json扩展名的情况下.先感谢您.

小智 5

我有相同的情况,但现在我找到了解决方案.现在我可以在没有.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();
    }
Run Code Online (Sandbox Code Playgroud)

现在在您的控制器中,您拥有所有发布的数据$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();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在函数结束时,您需要调用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
    }
Run Code Online (Sandbox Code Playgroud)

AppControlleras中定义所有变量

public $status = false;
public $message = '';
public $responseData = array();
public $code = 200;
public $errors = '';
Run Code Online (Sandbox Code Playgroud)

还有一件事要做:

Response.php (/vendor/cakephp/cakephp/src/Network/Response.php) 你需要编辑在586一行 echo $content;echo json_encode($content);_sendContent()功能.

而已.现在您可以将请求网址设置为 domain_name/project_name/users/index.