新田(プログラマー)
Skill:PHP / Java / JavaScript / PostgreSQL Like:絵を描くこと、ピアノ
Questions(質問用テーブル) | Comments(コメント用テーブル) |
---|---|
id question | id question_id comment(コメント内容) name(回答者) created_at |
Route::get('/admin/result/{questionId}', 'Admin\ResultController@index');
Route::match(['get', 'post'], '/admin/result/ajax/{questionId}', 'Admin\ResultController@ajax');
/Controllers/admin/ResultController.php
// 閲覧画面を表示
public function index(Request $request, $questionId){
$questionInfo = Question::where('id', $questionId)->first();
return view('/admin/result', [
'questionId' => $questionId,
'questionInfo' => $questionInfo
]);
}
// コメントリストを取得してJSON形式で返す
public function ajax(Request $request, $questionId){
$commentData = Comment::where('question_id', $questionId)->orderBy('created_at', 'desc')->get();
$json = ["commentData" => $commentData];
return response()->json($json);
}
/views/admin/result/index.blade.php
@extends('layouts.parent')
@include('layouts.head')
@section('content')
@section('header')
@endsection
@include('layouts.error')
{{$questionInfo->question}}
@section('pageJs')
@endsection
@endsection
@include('layouts.footer')
/js/admin/result/comment.js
$(function(){
get_data()
})
// コメントを取得
function get_data(){
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.get({
url: "/admin/result/ajax/" + questionId,
method: 'POST',
dataType: 'json'
})
.done(function(data){
// 前のコメントリストを削除
$('#comment-data').find('.comment-visible').remove();
// コメントリストをクローンして表示
for(var i = 0; i < data.commentData.length; i++){
var commentClone = $('#comment-list').clone(true).removeAttr('style').addClass('comment-visible');
commentClone.children('#name').first().append(data.commentData[i].name);
commentClone.children('#comment').first().append(data.commentData[i].answer);
$('#comment-data').append(commentClone);
}
})
.fail(function(){
})
// 5秒ごとに更新
setTimeout("get_data()", 5000);
}