Php 如何在ajax中为laravel使用DELETE方法
在Laravel项目中,我想使用ajax删除一个项。 我的路线是Php 如何在ajax中为laravel使用DELETE方法,php,jquery,ajax,laravel-5.3,Php,Jquery,Ajax,Laravel 5.3,在Laravel项目中,我想使用ajax删除一个项。 我的路线是 Route::resource('title','TitleController'); 这是我的ajax代码 $.ajax({ url:'title', type: 'post', data: {_method: 'delete', _token :token, id : id}, success:function(msg){ consol
Route::resource('title','TitleController');
这是我的ajax代码
$.ajax({
url:'title',
type: 'post',
data: {_method: 'delete', _token :token, id : id},
success:function(msg){
console.log(msg);
}
});
$.ajax({
url:"{{url('title/" +id+ "')}}", //----- OR url :"/title/"+id,
type: 'DELETE',
data: {_token :token},
success:function(msg){
console.log(msg);
}
});
那么,如何在ajax中使用DELETE方法和删除项目的参数呢?使用正确的路由名称,在url中传递id
url:{{route('title.destroy',['id'=>$title->id]}},
或
在控制器中,您可以执行类似的操作:
public function destroy($id)
{
Title:::find($id)->delete();
redirect()->to('/')->with('message','Successfully deleted the title');
}
由于您在javascript中有id,因此需要将其连接到url
完整代码:
$.ajax({
url:'{{url('title')}}'+id,
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
console.log(msg);
}
});
下面是已解决的ajax代码
$.ajax({
url:'title',
type: 'post',
data: {_method: 'delete', _token :token, id : id},
success:function(msg){
console.log(msg);
}
});
$.ajax({
url:"{{url('title/" +id+ "')}}", //----- OR url :"/title/"+id,
type: 'DELETE',
data: {_token :token},
success:function(msg){
console.log(msg);
}
});
可能重复的
类型:“DELETE”
而不是POST应该可以在不需要\u方法
字段的情况下工作。右apokryfos。我更新了已解决的代码:)当我在route中使用“resource”时,laravel会根据方法和参数自动调用函数。。。。因此,如果我可以准确地发送方法,我不需要在URL中使用特定的函数名。。。。我想知道。。。在Ajax中有任何进程是可能的吗#madalinivascu@Arafat你这是什么意思?你能发布你的控制器吗?你现在正在做的ajax是将id作为请求参数传递的,删除路径是title/{id}
nottitle
ya….但是像post或get方法一样,我们也需要delete方法来删除一个项目…对吗?我建议你使用url:{{url('title')}“+id,
根据我的回答,您的url是相对于当前路由的,如果您更改当前路由,您的ajax将被破坏,搜索相对于新路由的行。“{url('title/“+id+”)}}”