猿问

Laravel 覆盖渲染器视图

我希望只要在有视图('view')的地方发送 ajax 请求,而不是返回原始视图,它会返回一个 JSON


像那样:


/**

     * @param \Illuminate\Contracts\View\View $view

     * @return \Illuminate\Http\JsonResponse

     */

    protected function ajaxResponse (View $view)

    {

        return response()->json([

            'id' => $view->getData()['page'],

            'title' => $view->getData()['title'],

            'content' => $view->renderSections()['content'],

            'replacepage' => null,

        ]);

    }

但我绝对不知道该怎么做我不想在每个控制器中重复自己


我试图用我的视图替换视图,但它不起作用,因为我希望一切正常,但我无法恢复我的页面部分


<?php


namespace App\Extensions\View;


use Illuminate\View\View;


class AjaxView extends View

{

    /**

     * Get the contents of the view instance.

     *

     * @return string

     * @throws \Throwable

     */

    protected function renderContents()

    {

        if(request()->ajax()) {

            echo $this->getResponse($this->getData());

            exit;

        }


        return parent::renderContents();

    }


    /**

     * @param array $data

     * @return false|string

     */

    public function getResponse (array $data = [])

    {

        return json_encode([

            'id' => $data['page'],

            'title' => (!empty($data['title']) ? $data['title'] . ' - ' . config('app.name') : null),

            'content' => $this->renderSections()['content'],

            'replacepage' => null

        ]);

    }


}

这将返回:

交互式爱情
浏览 105回答 2
2回答

撒科打诨

也许你可以这样做:在app/Http/Controllers/Controller.php,添加方法response();protected function view($viewPath, $content, $status = 200, array $headers = []){&nbsp; &nbsp; &nbsp; &nbsp; if(request()->ajax()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return response()->json($content, $status, $headers);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return view($viewPath, $content);}然后你的控制器方法可以像这样使用:public function create(){&nbsp; // logic&nbsp; return $this->view('view_path', $data);}

森林海

我改变了你的功能protected function ajaxView(string $viewPath, array $content = [], int $status = 200, array $headers = [])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $view = view($viewPath, $content);&nbsp; &nbsp; &nbsp; &nbsp; if(request()->ajax()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dd($view->getData());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return response()->json([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'id' => $this->view->getData()['page'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title' => $this->view->getData()['title'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'content' => $this->view->renderSections()['content'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'replacepage' => null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ], $status, $headers);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return $view;&nbsp; &nbsp; }但是,如果记录不为空,如果我将 dd() 放在我的外部,则 dd() 记录数组为空
随时随地看视频慕课网APP
我要回答