虽然被接受的答案是正确的,但这个答案解释了如何在使用jQuery进行Ajax请求时更新
loic-sharma profiler。使用这种方法,不需要阅读文件日志。
步骤1
第一个问题是在每个Ajax请求中向客户端发送更新的分析器数据。可以通过Laravel应用程序的“after”事件来解决此问题。
app/filters.php:
App::after(function($request, $response)
{
if($response instanceof \Illuminate\Http\JsonResponse && Profiler::isEnabled()) {
$profiler = Profiler::getFacadeRoot();
$profilerJson = json_encode($profiler->render());
$content = substr($response->getContent(), 0, -1) . ',"profiler":' . $profilerJson . '}';
$response->setContent($content);
}
});
App::after
过滤器将在每个 Laravel 请求上运行。上面闭包的第一行确保它只会继续执行,如果响应是 JsonResponse 类型并且启用了分析器。如果是这种情况,则呈现分析器并将 HTML 附加到 JSON 对象中。
注意:此代码假定返回的 JSON 是对象。因此,对于数组,它将失败:Response::json(array(1,2,3))
。
步骤2
现在,更新后的分析器 HTML 正在发送到客户端,我们必须使用 JavaScript 更新 DOM 中的新分析器 HTML。每次客户端收到 JSON 响应时都应该发生这种情况。jQuery 提供全局 Ajax 事件处理程序,非常适合实现此目的。
$(document).ajaxSuccess(function(event, request, settings) {
try {
json = jQuery.parseJSON(request.responseText);
if(json.profiler) {
renderProfiler(json.profiler);
}
} catch(error) {
return;
}
});
以下是将旧的分析工具替换为新分析工具的方法:
以下是将旧的分析工具替换为新分析工具的方法:
renderProfiler = function(data) {
// Remove previous
$anbu = $('.anbu');
$anbu.prev().remove(); // Removes <style> tag of profiler
$anbu.next().next().remove(); // Removes the inline script tag of profiler
$anbu.next().remove(); // Removes jQuery script tag by the profiler
$anbu.remove(); // Removes the <div> tag of profiler
$(document.body).append(data);
};
使用方法
现在只需将响应返回为以下内容:
return Response::json(array(
'user' => Auth::user()
));
Laravel会追加性能分析器的HTML代码。Javascript将捕获JSON响应并更新DOM。您将在网页上看到SQL查询和时间。
注意
虽然代码经过测试,但可能会有一两个错误。这也不是我实际操作的完全方式。我不是在JSON响应中发送HTML,而是使用性能分析器的实际数据扩展对象。在客户端,我使用mustache模板来渲染性能分析器。
$bindings
作为Event::listen调用的函数的第二个参数传递。因此,... , function($sql, $bindings) { ...
。 - JeemusuLaravel 5
,请参阅此帖子:https://dev59.com/el4c5IYBdhLWcg3wl7Mg#34638344(附注:我很愚蠢,在使用5.2时尝试了这里的方法,希望其他人不要犯同样的错误) - ch271828n