如何使用ajax请求删除laravel 5.3中的记录? [英] How to delete record in laravel 5.3 using ajax request?
问题描述
我试图在laravel 5.3中使用ajax删除记录,我知道这是一个常见问题,并且已经有很多关于此主题的在线解决方案和教程.我尝试了其中的一些,但大多数都给了我相同的错误NetworkError: 405 Method Not Allowed
.我试图以不同的角度来完成这项任务,但是我被卡住了,找不到我错了,这就是为什么我将此问题添加为指导原则.
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.
我正在尝试使用以下脚本删除记录.
I'm trying following script for deleting the record.
Controller.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
Route::get('/user/delete/{id}', 'UserController@destroy');
可见
<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>
App.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");
});
当我单击删除按钮时,它在控制台中返回错误NetworkError: 405 Method Not Allowed
.如果没有ajax,则相同的删除功能将正常运行.
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.
任何人都可以引导我解决问题的地方,如果有人在此方面指导我,我将不胜感激.谢谢..
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..
推荐答案
使用Route::delete
代替使用Route::get
.
除此之外,在ajax调用中将type: 'Put'
更改为type: 'DELETE'
.
In addition to that change the type: 'Put'
to type: 'DELETE'
in the ajax call.
P.S.这段代码
$Users = new UserModel; // Totally useless line
$Users = UserModel::find($id); // Can chain this line with the next one
$Users->delete($id);
可以写为:
UserModel::find($id)->delete();
或更短:
UserModel::destroy($id);
请记住,->delete()
将触发事件,而::destroy()
不会触发事件.
Keep in mind that ->delete()
will fire an event while ::destroy()
will not.
这篇关于如何使用ajax请求删除laravel 5.3中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!