如何使用ajax在laravel中获取帖子?

时间:2017-04-14 05:28:19

标签: jquery ajax laravel

我成功地将ajax添加到laravel中,以下代码通过ajax添加了一个帖子,没有页面刷新,将其添加到数据库,但是我对如何获取通过ajax提交的帖子感到有点无能为力。

任何建议,没有错误显示,我只是不能通过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 );
      }
  }


}

Dashboard.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' => 'PostController@postCreatePost',
    'middleware' => 'auth'

]);

2 个答案:

答案 0 :(得分:1)

您可以非常轻松地使用laravel中的jquery ajax()来获取与帖子相关的数据或视图:

Jquery ajax():

$.ajax({
    url: 'url('/fetchposts')',
    type: "get",
    data: {
        key: value  // pass the data here if you have any like:
        //postId: postId,
        //name: name
    },
    success: function(data){

});

routes.php文件:

Route::get('/fetchposts',[
    'uses'=>'YourController@fetchPosts'
]);

YourController.php:

public function fetchPosts()
{
    // From this function either return the entire view with corresponding data into it
      $posts = Post::orderBy('created_at', 'desc')->get();

    // Or return the JSON array and make the view in success of ajax and appedn it to your html
      return response ()->json( $posts );
}

答案 1 :(得分:1)

<强> postcontroller.php

保存后获取帖子并将其返回给ajax

$post = new Post();
$post->body = $request->body; $request->user()->posts()->save($post);

//Retrieve Posts
$responsePosts = Post::all(); // or limit here how many posts you would like to send back

return response ()->json( $responsePosts );

<强> app.js

帖子数据将在

中提供
success: function (data) {
  var posts = JSON.parse(data);
  var temp = '';
  $.each(posts, function(prop, value) {
     temp += "<h4>"+posts['username']+"</h4>"+
             "<p class='post-body'>"+posts['body']+"</p>"+
             "<div class='info'>made on"+posts['created_at']+"</div>";
  });
  $("article.post").html(temp);

您可以通过附加

来填充帖子
<article class="post"></article>