2017-03-01 61 views
1

没有与URL mysite/dashboard与职位Lraravel从职位列表发送相同的AJAX请求,并从一个职位

路线

Route::get('dashboard', '[email protected]'); 

方法

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', '[email protected]'); 

js脚本

$(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); 
    } 
}); 
}); 

方法路线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 
     )); 
    } 

对于每一个列表中的所有代码工作就好了岗位。

而且我可以打开每一个岗位

路线

Route::get('dashboard/posts/{id}', '[email protected]'); 

方法DashboardController

public function show($id) { 
    $post = Post::findOrFail($id); 
    return view('dashboard.show', compact('post')); 
} 

和后也有发布按钮,但一个职位的js代码不起作用,因为它试图发送AJAX请求到url mysite/dashboard/posts/publish(不是mysite/publish)a当然失败了。如何让我的代码适用于帖子列表和一个帖子两者?

回答

1

如果问题是,AJAX请求不发送请求到mysite/publish,那么简单的办法是到以下网址相对使用站点根目录:/publish

所以,你只需要改变url: 'publish',url: '/publish',

+0

哦,那么容易...非常感谢! – Heidel

+0

很高兴帮助,欢呼! – Paras