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

zvokhttg  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(200)

我想从数据库中获取数据,并使用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);
    }
});
tcbh2hod

tcbh2hod1#

请尝试以下操作:
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

相关问题