2016-08-01 52 views
0

我正在使用资源控制器进行注释。 我有一个链接来删除我的刀片中的评论。是否可以使用laravel中的jquery重定向到资源控制器的销毁方法?

<a href="" ><span class="glyphicon glyphicon-trash delete"></span></a> 

如果我点击它的jQuery对话弹出窗口。对话框的代码如下。

jQuery(document).ready(function($){ 
    $('.edit-delete span.delete').click(function(e){ 
     e.preventDefault(); 
     $('<div id="dialog" class="pull-center"></div>').appendTo('body').html('<div"><h4>Are you sure you want to delete this comment?</h4></div>') 
     .dialog({   
      autoOpen: true, 
      modal : true, 
      title : 'Confirm', 
      buttons: { 
       "Yes" : function(){      
        $(this).dialog('close'); 
        $(location).attr("href", " {{what do i put here?}} "); 

       }, 
       "No" : function(){ 
        $(this).dialog('close'); 
       } 
      } 
     }); 


    }); 

}); 

但毫无疑问,作为重定向我们需要使用删除method.How实现将无法工作?

回答

0

在你{{what do i put here?}}部分,你会希望有一个链接到laravel路线,像这样

{{ route('routeName', ['id' => $comment->id]) }} 

看到https://laravel.com/docs/5.2/routing#named-routes

注意这将需要使用GET方法,但它可能是比较正常的使用表单,然后你可以使用PUT或DELETE,在这种情况下可能更有意义,或者我经常从这种请求中使用AJAX。

0

<a href="delete/{{$id}}(or whatever delete route you have)" data-method="delete" data-token="{{csrf_token()}}" data-confirm="Are you sure you want to delete this x ?"> 

然后你的路线即可。 我们需要在html中为csrf标记创建一个隐藏的输入字段。

<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}"> 

需要创建一个带有href的标签,如下所示。

<a class="js-ajax-delete" href="{{route('comment.destroy', $comment->id)}}" ><span class="glyphicon glyphicon-trash"></span></a> 

脚本应该是这样的:

jQuery(document).ready(function($){ 

    $('.js-ajax-delete').click(function(e){ 
     e.preventDefault(); 
     var deleteUrl = $(this).attr('href'); 
     var token = $('#token').val(); 

     $('<div id="dialog" class="pull-center"></div>').appendTo('body').html('<div"><h4>Are you sure you want to delete this comment?</h4></div>') 
     .dialog({ 

      autoOpen: true, 
      modal : true, 
      title : 'Confirm', 
      buttons: { 
       "Yes" : function(){ 

        $(this).dialog('close'); 

        $.ajaxSetup({ 
          headers: { 
           'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') 
          } 
         }); 

        //Delete request 
         $.ajax({ 
          type: 'DELETE', 
          url: deleteUrl, 
          data: { _token :token }, 
          success: function(data){ 
           if (data == "true") { 
           window.location.href=window.location.href; 
           }; 
          } 
         }); 
       }, 
       "No" : function(){ 
        $(this).dialog('close'); 
       } 
      } 
     });   

    }); 
}); 

,并在控制器的删除方法是这样的:

public function destroy($id) 
    { 
     $comment = Comment::find($id); 
     $comment->delete(); 
     session()->flash('success', 'Comment has been deleted'); 
     return "true";//it has to be a string 
    } 

运行,我们需要加载jQuery的对话框-UI和jQuery的课程。 希望它可以帮助别人。

相关问题