【问题标题】:CakePHP 3 and partial View update via Ajax - How it should be implemented?CakePHP 3 和通过 Ajax 的部分视图更新 - 应该如何实现?
【发布时间】:2017-06-08 17:24:14
【问题描述】:
我想通过 ajax 渲染一个 cakephp3 模板并将 html 注入到加载的页面中(不重新加载页面)。
根据
CakePHP 3 and partial View update via Ajax - How it should be done?,
这个想法可以是
为每个 ajax 操作创建专用模板 (*.ctp) 文件,渲染
它像任何其他动作一样,但没有主布局并注入
HTML(一种变体 1,但具有独立的 VC 逻辑)。
还提供了部分示例代码:
public function ajaxRenderAuditDetails($id = null)
{
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
谁能推荐一个完整的例子?
【问题讨论】:
标签:
ajax
partials
cakephp-3.x
【解决方案1】:
为此,您必须使用 Ajax 调用从服务器获取数据。就 CakePhp 而言,您将使用 Ajax 调用控制器函数。这个函数调用一个 ctp 文件来渲染你的局部视图。 Ajax 的成功函数应该更新或附加部分视图。这个过程的完整示例代码在这里 -
呼叫控制器功能的Ajax代码 -
$.ajax({
dataType: 'json',
url: basepath/controllername/controllerfunction,
type: "POST",
dataType : 'html',
success: function (data) {
$(selector).html(data);
}
});
public function ajaxRenderAuditDetails($id = null){
$this->viewBuilder()->layout(false);
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
把你需要的html或者逻辑放到ctp文件中。
这不是一个正在运行的代码。这是在 CakePhp 中更新部分视图的示例。