我希望只要在有视图('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
]);
}
}
这将返回:
撒科打诨
森林海