CakePHP 3 - 当调试模式 = true 时,无法 return 正确 json

CakePHP 3 - Can't return proper json when debug mode = true

我是 Whosebug 的新手,我刚刚开始使用 CakePHP 3。

我 运行 遇到了一个奇怪的问题:

我正在向控制器发送 ajax-请求(表单提交),我希望得到正确的 json- 响应。当我在 config/app.php 中将调试模式设置为 false 时它工作正常,但是当它设置为 true 时,我在浏览器控制台中收到一条错误消息,responsetext 似乎是 html.我在 url.

中调用带有 .json 扩展名的操作

我链接了控制台的屏幕截图,其中第一个响应是调试模式设置为 false,第二个响应设置为 true:

我已经在 config/routes 中启用了扩展。php:

Router::scope('/', function (RouteBuilder $routes) {
    $routes->extensions(['json', 'xml']);
(...)

这是控制器代码:

public function getUserStats() {
    $this->log($this->request->data, 'debug');

    if (($this->request->is('post'))) {
        $this->log('getCategories(): Post-request is received.', 'info');

        $usersTable = TableRegistry::get('Users');
        $q = $usersTable->find('statsByUsers', $this->request->data);
        $users = $q->all();

        // Calculating total amount per user.               
        foreach ($users as $u) {
            foreach ($u->purchases as $p) {
                $u->total += $p->total;
            }
        }

        $this->log($users, 'debug');

        $this->set('users', $users);
        $this->set('_serialize', ['users']);
    }
}

型号代码如下:

 public function findStatsByUsers(Query $query, array $options) {
    debug($options);
    $options['dates'] = $this->getConvertedDates($options);
    $query
        ->contain([
            'Purchases' => function($q) use($options) {
                return $q
                    ->select(['id', 'total' => 'amount * count', 'purchase_date', 'user_id'])
                    ->where(['purchase_date BETWEEN :fromDate AND :toDate',])
                    ->bind(':fromDate', $options['dates']['fromDate'], 'datetime') // Binds the dates to the variables in where-conditions
                    ->bind(':toDate', $options['dates']['toDate'], 'datetime');
            }
                ])
            ->where([
                'Users.id IN ' => $options['users'],
                'Users.active' => true
        ]);

    return $query;
}

我希望我已经给了你足够的信息,以便你能帮助我解决这个问题。

CakePHP 版本:3.3.2

<?php

use Cake\Core\Configure;

// your class ,...

public function getUserStats() {

        $this->log($users, 'debug');

        Configure::write('debug',false); // DISABLE

        $this->set('users', $users);
        $this->set('_serialize', ['users']);
}

查看屏幕截图中可见的输出位

<div class="cake-debug-output"> ...

HTML 是由 debug() 函数生成的输出。

仔细查看您的模型代码,您应该会发现对函数的调用。去掉它,应该就好了。

顺便说一句,可以在 <div> 中的第一个 <span> 元素中找到调用源,因此如果您以后遇到类似问题,请务必检查一下。