CakePHP4 Ajax:从控制器发送到视图

Posted

技术标签:

【中文标题】CakePHP4 Ajax:从控制器发送到视图【英文标题】:CakePHP4 Ajax: Send from Controller to View 【发布时间】:2021-12-20 16:38:45 【问题描述】:

我想从数据库中获取数据并使用 Cakephp4 中的 Ajax 从控制器发送到视图。

我已经实现了它(很少找到文档),但它没有返回数组。它想要一个完整的视图,但我不想创建一个完整的页面,只需返回数组即可。

错误: The view for CountriesController::getAll() was not found.

在我的src/controller/CountriesController.php

        public function getAll() 


        $results = $this->Countries->find('all', [
                    'contain' => ['PLZ']
                ]);

                $this->set(compact('results')); 
                $this->set('_serialize', 'results'); 
    

在我的template/countries/index.php

$.ajax(
    type: 'get',
    url: 'countries/getAll',
    beforeSend: function(xhr) 
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ,
    success: function(response) 
        if (response.error) 
            alert(response.error);
            console.log(response.error);
        
        if (response.content) 
            $('#target').html(response.content);
        
    ,
    error: function(e) 
        alert("An error occurred: " + e.responseText.message);
        console.log(e);
    
);

【问题讨论】:

this part of the manual 有帮助吗?也许this question?还是this one? 是的,谢谢你,对不起。我稍后会发布我的解决方案。 【参考方案1】:

试试这样的:

config/routes.php

$routes->prefix('Api', function (RouteBuilder $routes) 
    $routes->setExtensions(['json']);
    $routes->fallbacks(DashedRoute::class);
);

Controller/Api/CountriesController.php

public function getall()

    $countries = $this->Countries->find('all', [
        'contain' => ['PLZ']
    ]);

    $data = [
        'countries' => $countries,
    ];

    $this->set(compact('data'));
    $this->viewBuilder()->setOption('serialize', ['data']);

先看看这是否有效: /api/countries/getall.json

【讨论】:

以上是关于CakePHP4 Ajax:从控制器发送到视图的主要内容,如果未能解决你的问题,请参考以下文章