Laravel 5 Ajax 删除无效
Laravel 5 Ajax Delete not working
我遇到了一个奇怪的问题。我似乎无法通过 ajax 提交删除记录。我没有发现任何错误,因为这之前在 Laravel 4 上有效。我是否需要向该方法提供 CSRF 令牌?如果我将路线更改为 any 而不是 post 或删除并直接点击它,它将按预期删除。
{!! HTML::link(url(), 'Delete', array('class' => 'btn btn-delete', 'data-name' => $tile->tile_name, 'id' => $tile->id)) !!}
Ajax
var id = $this.attr('id');
// Submit delete request to route with id
$.post('edit/delete/' + id);
// Redirect to gallery
window.location.href = 'http://ims-tiles.dev/';
路线
$router->post('edit/delete/{id}', [
'as' => 'tile.destroy',
'uses' => 'TileController@destroy'
]);
销毁方法
public function destroy($id) {
$tile = Tile::find($id);
$tags = explode(' ', $tile->getTags());
$tagIds = [];
foreach($tags as $tag){
array_push($tagIds, $tile->getTagId($tag));
}
$tile->tags()->detach($tagIds);
$tile->delete();
}
Do I need to provide the CSRF token to the method?
是的,你知道。 Laravel 的默认 CSRF 保护适用于 AJAX POST/PUT/DELETE/etc。请求就像他们做非 AJAX 一样。
不用担心。谢谢@ceejayoz!我能够弄清楚,这对 ajax 请求的 headers 中未设置的 csrf 令牌有很大影响。以下资源对我感兴趣的人有所帮助。
http://laravel.com/docs/master/routing
http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
我遇到了一个奇怪的问题。我似乎无法通过 ajax 提交删除记录。我没有发现任何错误,因为这之前在 Laravel 4 上有效。我是否需要向该方法提供 CSRF 令牌?如果我将路线更改为 any 而不是 post 或删除并直接点击它,它将按预期删除。
{!! HTML::link(url(), 'Delete', array('class' => 'btn btn-delete', 'data-name' => $tile->tile_name, 'id' => $tile->id)) !!}
Ajax
var id = $this.attr('id');
// Submit delete request to route with id
$.post('edit/delete/' + id);
// Redirect to gallery
window.location.href = 'http://ims-tiles.dev/';
路线
$router->post('edit/delete/{id}', [
'as' => 'tile.destroy',
'uses' => 'TileController@destroy'
]);
销毁方法
public function destroy($id) {
$tile = Tile::find($id);
$tags = explode(' ', $tile->getTags());
$tagIds = [];
foreach($tags as $tag){
array_push($tagIds, $tile->getTagId($tag));
}
$tile->tags()->detach($tagIds);
$tile->delete();
}
Do I need to provide the CSRF token to the method?
是的,你知道。 Laravel 的默认 CSRF 保护适用于 AJAX POST/PUT/DELETE/etc。请求就像他们做非 AJAX 一样。
不用担心。谢谢@ceejayoz!我能够弄清楚,这对 ajax 请求的 headers 中未设置的 csrf 令牌有很大影响。以下资源对我感兴趣的人有所帮助。
http://laravel.com/docs/master/routing
http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/