「已注销」 2017-09-05 22:58
浏览 41
已采纳

在laravel 5.5中创建随机按钮

I'm working on project and in first page of my application is a block that shows one of the posts in random order, but there is also a button to refresh this random post and show another instead without user needs to refresh the page.

Now my question is, how to make that button works?

Here is my controller:

public function index() {
      $randomfood = Food::where('status', 1)->inRandomOrder()->take(1)->get();
      return view('welcome', compact('randomfood'));
}

This is my view:

@foreach($randomfood as $randfood)
         <div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randfood->image}}" class="thumbnail img-responsive" alt="food image"></a></div>
         <div class="col-md-8">
              <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randfood->title}}</a></h5>
              {!!  str_limit($randfood->description, 100) !!}
         </div>
         <div class="col-md-2 text-center">
              <p>Don't like?</p>
              <a class="bhover" href="#">Find another recipie</a>
         </div>
@endforeach

enter image description here

UPDATE:

JS code now is like this after checked from http://www.jslint.com/

$(document).ready(function () {
$( "a.bhover" ).click(function() {
$.ajax({
          url: "{{route('food.randompost')}}",
          data: {"token_": "{{Session::token()}}"}, //session token, neccesary to use POST request
          type: "food",
          success: function (data) {
             $("#live_content").empty(); //clean the actual post
             $("#live_content").append(data); // add new post from the controller
          },
          error: function(data){
              //handle errors here
          }
      });
});
});
});

Error in console:

SyntaxError: expected expression, got '}'[Learn More]

展开全部

  • 写回答

1条回答 默认 最新

  • duanjuelu8874 2017-09-05 23:31
    关注

    What you really want to do here is:

    public function index() {
          $randomfood = Food::where('status', 1)->inRandomOrder()->first();
          return view('welcome', compact('randomfood'));
    }
    

    So you can use your random food post as a single element instead of as collection. Let's add a div which wraps the desired live element to make it live:

    <div id="live_content">
                      <div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randomfood ->image}}" class="thumbnail img-responsive" alt="food image"></a></div>
                      <div class="col-md-8">
                        <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randomfood->title}}</a></h5>
                          {!!  str_limit($randomfood->description, 100) !!}
                      </div>
    </div>
                      <div class="col-md-2 text-center">
                          <p>Don't like?</p>
                          <a class="bhover" href="#">Find another recipie</a>
                      </div>
    

    Okey now, let's create a blade view to fill with the refreshed data, i.e. live.recipe.blade.php:

     <div class="col-md-2"><a href="{{ route('showrecipe', $food->slug) }}"><img src="{{url('/')}}/images/{{$randomfood ->image}}" class="thumbnail img-responsive" alt="food image"></a></div>
                          <div class="col-md-8">
                            <h5><a href="{{ route('showrecipe', $food->slug) }}">{{$randomfood->title}}</a></h5>
                              {!!  str_limit($randomfood->description, 100) !!}
                          </div>
    

    We need a route and a method to handle the ajax call in our controller so let's add it:

    web.php

    Route::post('update-post', 'YourController@updateRandomPost')->name('food.randompost');
    

    Controller

    public function updateRandomPost(Request $request) {
          $randomfood = Food::where('status', 1)->inRandomOrder()->first(); // get new random post
          return view('live.recipe', compact('randomfood')); //fill our live post template and retrieve it to the view
    }
    

    We gonna call this method by using an ajax call, add it on your scripts sections inside the view. Add a bind to the button's click action too:

    <script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>
    <script>
         $(document).ready(function () {
        $( "a.bhover" ).click(function() {
          $.ajax({
                    url: '{{route('food.randompost')}}', //our fresh route name
                    data: {"token_": '{{Session::token()}}'}, //session token, neccesary to use POST request
                    type: 'post',
                    success: function (data) {
                       $('#live_content').empty(); //clean the actual post
                       $('#live_content').append(data); // add new post from the controller
                    },
                    error: function(data){
                        //handle errors here
                    }
                });
        });
    
        });
    </script>
    

    And that's all IMO, let me know if you don't undersand something

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部