CakePHP4 Ajax: 从控制器发送到视图
CakePHP4 Ajax: Send from Controller to View
我想从数据库中获取数据并使用 CakePhp4 中的 Ajax 从控制器将其发送到视图。
我已经实现了它(很少找到文档)但它没有 return 我的数组。它想要一个完整的视图,但我不想创建一个完整的页面,只是 return 数组。
错误:
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);
}
});
尝试这样的事情:
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 从控制器将其发送到视图。
我已经实现了它(很少找到文档)但它没有 return 我的数组。它想要一个完整的视图,但我不想创建一个完整的页面,只是 return 数组。
错误:
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);
}
});
尝试这样的事情:
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