ajaxをlaravelに追加できました。次のコードでは、ページをリフレッシュせずにajax経由で投稿を追加してデータベースに追加しますが、ajax経由で投稿した投稿を取り出す方法は少しわかりません。ajaxを使用してlaravelで投稿を取得する方法は?
任意の提案エラーが現れていない、私はちょうど、AJAX経由
app.js
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#add').click(function(){
$.ajax({
url: 'createpost',
type: "post",
data: {'body':$('textarea[name=body]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
$('#new-post').val('');
}
});
});
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;
class PostController extends Controller
{
public function getDashboard()
{
$posts = Post::orderBy('created_at', 'desc')->get();
$cookie = cookie('saw-dashboard', true, 15);
$users = User::all();
$user = new User();
// return view('dashboard', array('user'=> Auth::user()), compact('users'))->withCookie($cookie);
return view('dashboard',array('user'=> Auth::user(), 'posts' => $posts, compact('users')))->withCookie($cookie);
}
public function postCreatePost(Request $request) {
$rules = array(
'body' => 'required|max:1000'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Response::json (array(
'errors' => $validator->getMessageBag()->toArray()
));
} else {
$post = new Post();
$post->body = $request->body;
$request->user()->posts()->save($post);
return response()->json($post);
}
}
}
ダッシュボードポストをフェッチカント.blade.php
@extends('layouts.layout')
@section('title')
Dashboard
@endsection
@section('content')
<div class="dashboard eli-main">
<div class="container ">
<div class="row">
<div class="col-md-6 col-md-12">
<h1>{{$user->username}}</h1>
<h4>What do you have to say?</h4>
<form>
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your Post"></textarea>
</div>
<button type="button" id="add" class="mybtn2">Create Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
{{ csrf_field() }}
@foreach($posts as $post)
<article class="post">
<h4>{{$post->user->username}}</h4>
<p class="post-bod">
{{ $post->body }}
</p>
<div class="info">
made on {{ date('F d, Y', strtotime($post->created_at)) }}
</div>
</article>
@endforeach
</div>
</div>
</div>
</div>
@endsection
、ここでルート
Route::post('/createpost',[
'uses' => '[email protected]',
'middleware' => 'auth'
]);
に付加することにより、バックポストを埋めることができ、あなたは、AJAXを経由して、すべての記事を検索しますか? – linktoahref
@linktoahref、whats up man、あなたは私を少し前に助けてくれました。まあまあですが、私はそれに限界を置くことができると確信しています。 – BARNOWL
Onsuccessは取得したデータをdivに追加します。 – Bugfixer