Cakephp3: How can I return json data?

前端 未结 8 3009
不思量自难忘°
不思量自难忘° 2021-02-19 09:39

I am having a ajax post call to a cakePhp Controller:

$.ajax({
                type: \"POST\",
                url: \'locations/add\',
                data: {
           


        
相关标签:
8条回答
  • 2021-02-19 10:15

    As of cakePHP 4.x.x the following should work assuming that your controller and routes are set as shown below: controller: <your_project_name>/src/Controller/StudentsController.php

    public function index()
        {
            $students = $this->Students->find('all');
            $this->set(compact('students'));
            $this->viewBuilder()->setOption('serialize',['students']);
        }
    

    Routes: <your_project_name>/config/routes.php

    <?php
    
    use Cake\Routing\Route\DashedRoute;
    use Cake\Routing\RouteBuilder;
    
    /** @var \Cake\Routing\RouteBuilder $routes */
    $routes->setRouteClass(DashedRoute::class);
    
    $routes->scope('/', function (RouteBuilder $builder) {
     
        $builder->setExtensions(['json']);
        $builder->resources('Students');
        $builder->fallbacks();
    });
    

    Run bin/cake server and visit http://localhost:8765/students.json using postman/insomnia or just the normal browser. See further documentation for setting up Restful controllers and Restful Routing

    Don't forget to set the method to GET on postman and insomnia.

    0 讨论(0)
  • 2021-02-19 10:16

    When you return JSON data you need to define the data type and response body information like below:

    $cardInformation = json_encode($cardData);
    $this->response->type('json');
    $this->response->body($cardInformation);
    return $this->response;
    

    In you case just change this return json_encode(array('result' => 'success')); line with below code:

    $responseResult = json_encode(array('result' => 'success'));
    $this->response->type('json');
    $this->response->body($responseResult);
    return $this->response;
    
    0 讨论(0)
提交回复
热议问题