2017-03-01 51 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