Laravel - 通过 ajax 使用自定义 ID 加载 post
Laravel - load post with custom id via ajax
我想在单击 post link 时通过 AJAX 加载我的 post,如何通过 AJAX?
我的 Blade 文件中有一个 link:
{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}
我有以下路线定义:
Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController@show']);
控制器动作:
public function show($id, $slug = null)
{
$post = $this->news->getById($id, 'news');
if ($slug != $post->slug){
return Redirect::route('news', ['id' => $post->id, 'slug' => $post->slug]);
}
Event::fire('posts.views', $post);
return View::make('post/post', compact('post'));
}
然后我正在尝试这个:
var postTitle = $(".link--to--post");
postTitle.click(function () {
$.ajax({
url: '/news/{id}-{slug}',
type: 'GET',
data: $(this),
success: function (data) {
console.log(data)
}
});
return false;
});
但这对我不起作用,我做错了什么?
您的 javascript 应该像这样传递参数:
$.ajax({
url: '/news/' + id + '-' + slug,
success: function (data) {
console.log(data)
}
});
您有 url: '/news/{id}-{slug}'
,它会向 /news/{id}-{slug}
执行 GET 请求,这不是有效路由 -- 您需要 URL,例如 /news/1-foo
。
我想在单击 post link 时通过 AJAX 加载我的 post,如何通过 AJAX?
我的 Blade 文件中有一个 link:
{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}
我有以下路线定义:
Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController@show']);
控制器动作:
public function show($id, $slug = null)
{
$post = $this->news->getById($id, 'news');
if ($slug != $post->slug){
return Redirect::route('news', ['id' => $post->id, 'slug' => $post->slug]);
}
Event::fire('posts.views', $post);
return View::make('post/post', compact('post'));
}
然后我正在尝试这个:
var postTitle = $(".link--to--post");
postTitle.click(function () {
$.ajax({
url: '/news/{id}-{slug}',
type: 'GET',
data: $(this),
success: function (data) {
console.log(data)
}
});
return false;
});
但这对我不起作用,我做错了什么?
您的 javascript 应该像这样传递参数:
$.ajax({
url: '/news/' + id + '-' + slug,
success: function (data) {
console.log(data)
}
});
您有 url: '/news/{id}-{slug}'
,它会向 /news/{id}-{slug}
执行 GET 请求,这不是有效路由 -- 您需要 URL,例如 /news/1-foo
。