删除db中的行时出现TokenMismatchException

时间:2015-12-19 18:28:03

标签: php ajax laravel token csrf-protection

我正在使用DropZone.js和laravel。当我尝试删除带有AJAX请求的记录时,我得到一个回复​​说:

  哎呀,好像出了什么问题。 1/1 TokenMismatchException in   VerifyCsrfToken.php

var classElements = document.querySelectorAll("tr.ui-selected td.filename");

        for(var x = 0;x < classElements.length;x++){
            var result;
            result = classElements[x].innerHTML;
            var csrf = $('input[name=_token]').val();
            $.ajax({
                async: true,
                type: "DELETE",
                method: 'POST',
                url: '../public/deletefile',
                data: { filename: result, "_token": "{{ csrf_token() }}"  },
                success: function(response) {
                   $('#results').html(response);
                }
            });

这是模型:

public function deleteUserFiles(){ 
        $userid = Auth::id();
        $result = $_POST['result'];
        $deletedRows = App\Models\File::where('filename', $result)->where('userid', $userid)->delete();
    }
}

路线:

Route::post('deletefile', 'UserFiles@deleteUserFiles');

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是你在循环中使用csrf_token()。我认为您的JS代码应如下所示:

var classElements = document.querySelectorAll("tr.ui-selected td.filename");
var csrf = $('input[name=_token]').val();

for(var x = 0;x < classElements.length;x++){
    var result;
    result = classElements[x].innerHTML;

    $.ajax({
        async: true,
        type: "DELETE",
        method: 'POST',
        url: '../public/deletefile',
        data: { filename: result, "_token": csrf  },
        success: function(response) {
           $('#results').html(response);
        }
    });