受け入れられた回答は正しいですが、この回答では、 jQuery を使用して Ajax リクエストを行うときにloic-sharma プロファイラーを更新する方法について説明しています。このアプローチを使用すると、ファイル ログを読み取る必要がなくなります。
ステップ1
最初の問題は、Ajax 要求ごとに更新されたプロファイラー データをクライアントに送信することです。これは、Laravel アプリケーションの「after」イベントを使用して解決できます。
app/filters.php:
App::after(function($request, $response)
{
// If it's a JsonResponse and the profiler is enabled, include it in the 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 を使用して新しいプロファイラー HTML で DOM を更新する必要があります。これは、クライアントが JSON 応答を受け取るたびに発生するはずです。jQuery は、これを実現するのに最適なグローバル Ajax イベント ハンドラーを提供します。
$(document).ajaxSuccess(function(event, request, settings) {
try {
json = jQuery.parseJSON(request.responseText);
if(json.profiler) {
renderProfiler(json.profiler);
}
} catch(error) {
// Its not JSON.
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 を更新します。Web ページで SQL クエリとタイミングを確認できます。
ノート
コードがテストされている間、1 つまたは 2 つのバグが存在する可能性があります。これも私のやり方ではありません。JSON 応答で HTML を送信する代わりに、プロファイラーからの実際のデータでオブジェクトを拡張します。クライアント側では、口ひげのテンプレートを使用してプロファイラーをレンダリングします。