「已注销」 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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?