我正在處理項目,並在我的應用程序的第一頁中顯示隨機順序中的一個帖子,但也有一個按鈕用於刷新此隨機帖子並顯示另一個帖子而不需要用戶刷新頁面。在laravel中創建隨機按鈕5.5
現在我的問題是,如何使該按鈕的作品?
這裏是我的控制器:
public function index() {
$randomfood = Food::where('status', 1)->inRandomOrder()->take(1)->get();
return view('welcome', compact('randomfood'));
}
這是我的看法:
@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
UPDATE:
JS代碼,現在就像是從這個檢查後, 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
}
});
});
});
});
錯誤控制檯:
SyntaxError: expected expression, got '}'[Learn More]
使用Ajax調用刷新隨機職位。 –
@SagarGautam你能幫我怎麼做嗎? – mafortis
由於您知道從數據庫中獲取隨機發布的邏輯。點擊按鈕時,您必須檢測javascript中按鈕點擊的事件,並對調用函數的路由進行ajax調用。在這個函數中,你需要編寫代碼來獲得隨機的帖子,並將隨機的帖子作爲來自函數的json響應返回。之後,在ajax的成功函數上,你必須編寫代碼來刷新html中的當前發佈數據和來自json響應的數據。希望你能理解。 –