当我点击帖子链接时,我想通过AJAX加载我的帖子,我如何通过AJAX发送我的帖子ID?
我的Blade文件中有一个链接:
{{ 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;
});
但这对我不起作用,我做错了什么?
答案 0 :(得分:2)
你的javascript应该传递这样的参数:
$.ajax({
url: '/news/' + id + '-' + slug,
success: function (data) {
console.log(data)
}
});
您有url: '/news/{id}-{slug}'
,它会向/news/{id}-{slug}
执行GET请求,这不是有效路由 - 您需要像/news/1-foo
这样的网址。