CakePHP 3 and partial View update via Ajax - How i

2019-09-04 04:22发布

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:

  1. Render required part of the view in dedicated controller action and simply inject the HTML.
  2. 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).
  3. 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?

0条回答
登录 后发表回答