网页上有网址mysite/dashboard
,其中包含帖子列表
路线
Route::get('dashboard', 'DashboardController@index');
方法
public function index() {
$posts = Post::latest('published_at')->unpublished()->paginate(20);
return view('dashboard.index', compact('posts'));
}
列表中的每个帖子都有发布
按钮<button type="button" class="btn btn-primary btn-publish-post">Publish</button>
方法路线
Route::post('publish', 'PostsController@publish');
js script
$(document).on('click', '.btn-publish-post', function(){
var $btn = $(this);
var post_id = $(this).closest('.post').data('post-id');
$btn.prop('disabled', true);
$.ajax({
type: 'post',
url: 'publish',
data: {'id' : post_id},
dataType: 'json',
success: function(response){
if(response.success) {
$btn.closest('.post').remove();
}
if(response.fail) {
}
$btn.prop('disabled', false);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
$btn.prop('disabled', false);
}
});
});
<{1}} 中的方法
PostsController
对于列表中的每个帖子,所有代码都可以正常工作。
但我也可以打开每一个帖子
路线
public function publish(Request $request)
{
$id = $request->get('id');
$published = Post::where('id', $id)
->update(['is_published' => 1]);
if ($published) {
return Response::json(array(
'success' => true
));
}
return Response::json(array(
'fail' => true
));
}
<{1}} 中的方法
Route::get('dashboard/posts/{id}', 'DashboardController@show');
并且该帖子还有发布按钮,但对于一个帖子js代码并不起作用,因为它尝试向网址DashboardController
发送AJAX请求(不是{{1} })当然失败了。如何使我的代码适用于帖子列表和一个帖子?
答案 0 :(得分:1)
如果问题是AJAX请求没有将请求发送到mysite/publish
,那么简单的解决方法是使用以下网址相对于网站根目录:/publish
因此,您只需将url: 'publish',
更改为url: '/publish',