我正在使用资源控制器进行评论。 我有一个删除我的刀片中的评论的链接。
<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');
}
}
});
});
});
但毫不奇怪重定向不起作用,因为我们需要使用Delete方法。如何实现呢?
答案 0 :(得分: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
答案 1 :(得分:0)
您可以使用此方法:https://gist.github.com/JeffreyWay/5112282 使用链接删除评论或其他内容。在标题的某处包含上面链接中提供的javascript,并在您的视图中放置html链接:
<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 ?">
然后您的路线可以是:
Route::delete('delete/{id}','your_controller@your_delete_method');
答案 2 :(得分:0)
找到解决方案。 我们需要在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');
}
}
});
});
});
并且控制器中的delete方法如下:
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 ofcourse。 希望它可以帮到某人。