我想使用ajax从数据库中删除一些数据..我已经完成了以下步骤来运行..但是当我试图删除它时,显示以下错误:
无法加载资源:服务器响应状态为404 (未找到)
这是我的路线:
Route::post('/delete/{id}',[
'uses'=>'ItemController@delete',
'as' => 'delete'
]);
这是控制器:
public function delete($id)
{
Item::find($id)->delete();
return Redirect::back();
}
这是我的观点页面:
<html>
<head>
<title> Item List</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
@foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->title }}</td>
<td>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" id="Reco" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
@endforeach
</tbody>
</table>
</div>
<script>
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/delete/'+id,
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
如果有人发现我已经完成的错误,希望您能帮助我找到它。
答案 0 :(得分:3)
通常在删除时传递参数不是一个好主意。因为我们可以通过网址删除数据,例如/delete/4
,而您可能只想在点击删除按钮后删除。
$.ajax({
type: "POST",
url: "{{url('/delete)}}",
data:{id:id}
success: function(result) {
console.log(result);
}
});
路线:
Route::post('/delete',[
'uses'=>'ItemController@delete',
'as' => 'delete'
]);
和控制器
public function delete(Request $request)
{
$id=$request->id;
Item::where(['id'=>$id])->delete();
return Redirect::back();
}
答案 1 :(得分:2)
试试这段代码:
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url:"{{url('delete')}}",
data:{id:id},
success: function(result) {
location.reload();
}
});
}
答案 2 :(得分:1)
试试这段代码
function deleteItem(id) {
var _token = $("input[name='_token']").val();
$.ajax({
type: "POST",
url: '/task/'+id,
data: '_method=DELETE&_token=' + _token,
success: function (result) {
console.log(result);
}
});
}
答案 3 :(得分:0)
试试这个:
$.ajax({
type: "POST",
url: url('/delete'), // The correct way to call ajax function in laravel
data:{
id: id
},
success: function(result) {
console.log(result);
}
});
答案 4 :(得分:0)
您可以在控制器中设置方法destroy,laravel会自动使用该方法进行删除。它接受id。
public function destroy($id){
Item::find($id)->delete();
echo 'Deleted Successfully.';
}
对于ajax,只需使用您的令牌发送方法删除。
jQuery.ajax({
url:'your-controller-route/id',
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
// do stuff
}
});