在我網站的主頁上有一個鏈接「獲取隨機故事」<a href="#" class="btn-get-random-post">Get Random Story</a>
,點擊我需要從數據庫中隨機發布並在同一個窗口中顯示。 我使用Laravel 5.4。Laravel 5隨機發帖
class PostsController extends Controller
{
public function index() {
return redirect('/');
}
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->first();
return view('posts.show', compact('post'));
}
}
路線
Route::get('posts', '[email protected]');
Route::get('posts/create', '[email protected]');
Route::get('posts/{id}', '[email protected]');
Route::post('posts', '[email protected]');
Route::post('publish', '[email protected]');
Route::post('delete', '[email protected]');
Route::post('get-random-post', '[email protected]');
JS
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.btn-get-random-post').on('click', function(){
$.ajax({
type: 'post',
url: './get-random-post',
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
});
});
而且我有2個問題在這裏
1.方法getRandomPost()
返回崗位,但如何顯示呢?我想要得到結果頁面的網址mysite/post/{id}
像來自方法show
的網址。
2.是否有任何方式獲取並顯示隨機帖子(與網址mysite/post/{id}
)沒有AJAX?
UPD
控制器
class PostsController extends Controller
{
public function index() {
return redirect('/');
}
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show', compact('post'));
}
public function getRandomPost() {
$post = Post::inRandomOrder()->first();
return redirect()->route('posts.show', ["id" => $post->id]);
}
}
主頁上的鏈接 <a href="{{ action('[email protected]') }}">Random Story</a>
路線
Route::get('/', '[email protected]');
Route::get('posts', '[email protected]');
Route::get('posts/create', '[email protected]');
Route::get('posts/{id}', '[email protected]')->name('posts.show');
Route::post('posts', '[email protected]');
Route::post('publish', '[email protected]');
Route::post('delete', '[email protected]');
Route::post('get-random-post', '[email protected]');
Route::post('dashboard/delete', '[email protected]');
Route::post('dashboard/unpublish', '[email protected]');
Route::post('dashboard/restore', '[email protected]');
該方法不允許錯誤通常指的是您在控制器上使用無效方法的情況,例如使用post調用get方法。看到你的路由定義,情況就是這樣。更改get-random-post爲GET – zedling