CakePHP 3 and partial View update via Ajax - How it should be done?

蹲街弑〆低调 提交于 2019-12-25 08:48:10

问题


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?

来源:https://stackoverflow.com/questions/37697753/cakephp-3-and-partial-view-update-via-ajax-how-it-should-be-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!