问题
One more time I have bumped into the problem how partial view upadtes via ajax should be done in CakePHP3. From my point of view, there are 3 ways of doing this:
- Render required part of the view in dedicated controller action and simply inject the HTML.
- Create dedicated template (*.ctp) file for every ajax action, render it like any other action but without the main layout and inject the HTML (kind of variant 1 but with separated VC logic).
- Return only required data as an ajax response (eg. entity data) and build part of my view from javascript on client side.
I think that the most efficient solution will be variant 2 because of separation of controller and view logic. Variant 1 would most probably cause view beeing built twice (on demand, and after request is processed) like in following snipped:
public function ajaxRenderAuditDetails($id = null)
{
if ($id == null) {
return null;
}
if ($this->request->is("ajax")) {
$this->set("result", $this->viewBuilder()->build()->cell("audits", [$id]));
}
}
Variant 3 on the other hand will double the view code in some cases - for example the same html will be genrated in ViewCell as well as on client side javascript What are the best practices for handling such functionality?
来源:https://stackoverflow.com/questions/37697753/cakephp-3-and-partial-view-update-via-ajax-how-it-should-be-done