php 如何使用ajax请求删除laravel 5.3中的记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39350918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete record in laravel 5.3 using ajax request?
提问by Ayaz Shah
I'm trying to delete record using ajax in laravel 5.3, i know this is one of the common question and there is already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me same error NetworkError: 405 Method Not Allowed
. I tried to do this task by different angle but i'm stuck and could not found where i'm wrong, that's why i added this question for guideline.
我正在尝试在 laravel 5.3 中使用 ajax 删除记录,我知道这是常见问题之一,并且已经有很多关于此主题的在线解决方案和教程。我尝试了其中的一些,但大多数都给了我同样的错误NetworkError: 405 Method Not Allowed
。我试图从不同的角度来完成这个任务,但我被卡住了,找不到我错的地方,这就是为什么我添加了这个问题作为指导。
I'm trying following script for deleting the record.
我正在尝试使用以下脚本来删除记录。
Controller.php
控制器.php
public function destroy($id)
{ //For Deleting Users
$Users = new UserModel;
$Users = UserModel::find($id);
$Users->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
}
Routes.php
路由.php
Route::get('/user/delete/{id}', 'UserController@destroy');
In View
在视图中
<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>
App.js
应用程序.js
$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'PUT',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
When i'm click on delete button it returning me error NetworkError: 405 Method Not Allowed
in console. Without ajax same delete function is working properly.
当我单击删除按钮时,它会NetworkError: 405 Method Not Allowed
在控制台中返回错误。没有 ajax 相同的删除功能工作正常。
Can anyone guide me where i'm wrong that i can fix the issue, i would like to appreciate if someone guide me regarding this. Thank You..
任何人都可以指导我在哪里我可以解决问题,如果有人指导我,我将不胜感激。谢谢你..
回答by siannone
Instead of using Route::get
use Route::delete
.
而不是使用Route::get
use Route::delete
。
In addition to that change the type: 'Put'
to type: 'DELETE'
in the ajax call.
除此之外,更改ajax 调用中的type: 'Put'
to type: 'DELETE'
。
P.S. This code
PS此代码
$Users = new UserModel; // Totally useless line
$Users = UserModel::find($id); // Can chain this line with the next one
$Users->delete($id);
can be written as:
可以写成:
UserModel::find($id)->delete();
Or even shorter:
或者更短:
UserModel::destroy($id);
Keep in mind that ->delete()
will fire an event while ::destroy()
will not.
请记住,它->delete()
会触发一个事件,而::destroy()
不会触发。
回答by Koushik Das
Make sure to add this in the meta
tag of your view
确保将此meta
添加到您的视图标签中
<meta name="csrf-token" content="{{ csrf_token() }}">
In your Routes
, do this
在您的Routes
, 执行此操作
Route::delete('/user/delete/{id}', 'UserController@destroy');
In your controller, do this
在您的控制器中,执行此操作
UserModel::destroy($id);
or
或者
DB::table('table_name')->where('id', $id)->delete();
Make sure to check that the user who is deleting the account actually owns the account a.k.a run authorization test.
确保检查删除帐户的用户实际上拥有该帐户,即运行授权测试。
Since it's a delete
request, you would require to send the csrf_token
along with your ajax header as the official site states.
https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token
由于这是一个delete
请求,因此您需要将csrf_token
ajax 标头与官方网站声明的一样发送。
https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token
Make sure to add this before the ajax call
确保在 ajax 调用之前添加
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now send the request
现在发送请求
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax(
{
url: "user/delete/"+id,
type: 'delete', // replaced from put
dataType: "JSON",
data: {
"id": id // method and token not needed in data
},
success: function (response)
{
console.log(response); // see the reponse sent
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
I hope this helps.
我希望这有帮助。
回答by Ganesh Khartode
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE', // Just delete Latter Capital Is Working Fine
dataType: "JSON",
data: {
"id": id // method and token not needed in data
},
success: function (response)
{
console.log(response); // see the reponse sent
},
error: function(xhr) {
console.log(xhr.responseText); // this line will save you tons of hours while debugging
// do something here because of error
}
});
});
});
回答by Rodrigo Butta
i'm resuming a working flow of deletion, with a request VERB. Hope it helps
我正在使用请求动词恢复删除工作流程。希望能帮助到你
and theres a commented code in the controller that could handle an ajax request
控制器中有一段注释代码可以处理 ajax 请求
In the form (with blade):
在形式(带刀片):
{{ Form::open(['method' => 'DELETE', 'route' => ['admin.products.edit', $product->id], 'name' => 'delete']) }}
{{ Form::close() }}
Route:
路线:
Route::delete('admin/products/{id}/edit', ['as' => 'admin.products.edit', 'uses' => 'Product\ProductController@delete']);
ProductController:
产品控制器:
public function delete($id)
{
// if (Request::ajax()) {
// if (Request::isMethod('delete')){
$item = Product::findOrFail($id);
$item->delete();
return redirect()->route('admin.products')->with('flashSuccess', 'deleted');
}
In the redirect part, i'm going back to my list page (admin.products) with a success notifier. The route would be:
在重定向部分,我将使用成功通知程序返回到我的列表页面 (admin.products)。路线是:
Route::get('admin/products', ['as' => 'admin.products', 'uses' => 'Product\ProductController@getList']);
So you can complete the flow.
这样就可以完成流程了。