我应该如何在 CakePHP 的视图中使用 requestAction 3.x

How should I use requestAction in the view with CakePHP 3.x

我的代码:

// View/Activities/index.ctp
...
<div>
    <?php echo $this->requestAction('/Activities/ajax_list/'.$categoryId,['return']);?>
</div>
...

//View/Activitest/ajax_list.ctp
....
<?php echo $this -> Html -> image("/img/add1.jpg"); ?>
...
<?php echo $this->Html->link('add_project', array('controller'=>'projects', 'action'=>'add', $categoryId)); ?>
....

我想将视图'ajax_list'包含到'index'中,它已经显示了,但是图像url和link是错误的。

然后我调试 Cake/Routing/RequestActionTrait.php , "requestAction" 函数我发现“$request = new Request($params);” $request->base , $request->webroot 为空。

谁能告诉我该如何解决?

新请求中未设置的 $base/$webroot 属性可能被认为是错误,或者文档可能只是缺少适当的示例解决方案,我无法确定,您可能想 report this over at GitHub 看看开发者怎么说。

使用视图单元格代替 requestAction()!

只要适用,您最好使用视图单元而不是请求操作,因为它们避免了调度新请求所带来的所有开销。

Cookbook > Views > View Cells

没有涉及模型?使用元素!

如果不涉及任何模型,而您所做的只是生成 HTML,那么您可以简单地使用元素。

Cookbook > Views > Elements

修复requestAction()

一种可能的解决方法是使用调度程序筛选器,用必要的值填充空的 $base/$webroot 属性,例如

src/Routing/Filter/RequestFilterFix.php

namespace App\Routing\Filter;

use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;

class RequestFixFilter extends DispatcherFilter
{
    public function beforeDispatch(Event $event)
    {
        $request = $event->data['request'];
        /* @var $request \Cake\Network\Request */

        if ($request->param('requested')) {
            $request->base = '/pro';
            $request->webroot = '/pro/';
            $request->here = $request->base . $request->here;
        }
    }
}

config/bootstrap.php

// ...

// Load the filter before any other filters.
// Must at least be loaded before the `Routing` filter.
DispatcherFactory::add('RequestFix');

DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');
// ...

另见 Cookbook > Routing > Dispatcher Filters > Building a Filter