「已注销」 2017-09-06 06: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-06 07: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

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?