ajax - 拉拉维尔 : cannot create correct DELETE action request

标签 ajax laravel-5

无法在 Laravel 中创建删除操作。

我得到Not FoundToken mismatch总是出错。

我的 Controller :

class TranslationController extends Controller
{
    public function destroy($id)
    {       
        //$id = 1;
        /*$translation = Translation::find($id);
        $translation->delete();*/
    }
    ....
}

Ajax 调用:

/* Delete given translation */
    var url = "translation";
    var id = 1; 

    $.ajax({
        method: 'DELETE',
        url: url + '/' + id,
        // data: {'id': id, '_token': token},
        success: function() {

        }
    });

这将给出:TokenMismatchException in VerifyCsrfToken.php line 53:

如果我尝试:

url: url + '/' + id,            
data: {'_token': token},  // token is equal to csrf_token

我有:NotFoundHttpException in Controller.php line 269:

路线:

Route::controller('translation', 'TranslationController');

否则我使用 Laravel 5 默认中间件,我没有更改与 csrf 相关的任何内容。

最佳答案

NotFoundHttpException意味着尚未指定带有特定 HTTP 谓词的特定请求的路由,或者未指定的操作(即 Controller 方法)被映射到动词,因为路由被错误地实现了。

既然您在帖子中提到 TranslationController定义为 implicit controller ,

Route::controller('translation', 'TranslationController');

从您发布的 Controller 代码来看,很明显您没有为 destroy 定义动词 Controller 中的方法 TranslationController .

如果您执行php artisan route:list在带有终端/命令行界面的项目根目录中,您将看到已注册的 HTTP 动词的列表、映射到相应的 URI 以及操作。

要在隐式 Controller 中定义特定方法,动词( GETPUTPOSTDELETE )应位于实际函数名称之前。 确保destroy方法在您的 Controller 中如下所示:

public function deleteDestroy($id){  
   //delete logic for the resource
}

注意: Laravel 默认情况下要求 csrf token 与特定的 RESTful 请求一起传递,因此请勿删除 data: {'_token': token}来自您的AJAX打电话。

更新

忘记提及url AJAX 调用中的 也应该更改为以下内容才能工作,因为这就是 Laravel 的隐式 Controller 定义 DELETE 的路由的方式请求:

var url = "translation/destroy";

关于ajax - 拉拉维尔 : cannot create correct DELETE action request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34853053/

相关文章:

jquery - 如何终止 DataTables 中之前的 AJAX 调用

javascript - 网站上的动态表格

php - Laravel 模型事件不会触发

linux - CentOS配置Nginx加载Laravel 5.8 Site

php - 拉维尔 5 : Replace string in query results (Eloquent ORM)

javascript - Toastr 使用 Laravel session 变量作为警报消息

php - 共享网络驱动器作为 Laravel 5.4 存储

javascript - .show() 在 ajax 调用后不工作

javascript - 如何让 AngularJS 忽略 ajax OPTIONS 方法?

asp.net - 来自 javascript PageMethods 的自定义 C# 数据传输对象