在我网站的主页上有一个链接“获取随机故事”<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