首页 > 解决方案 > 如何在 Laravel 6 中使用 Ajax 删除没有表单的项目

问题描述

我想在 Laravel 6 中使用使用 Ajax 的表单删除一个项目在我的路线中我有

Route::group(['middleware' => 'auth'], function() { 
    Route::get('/dashboard/desfazer-importe', 'DeleteImportController@index')->middleware('auth');
    Route::delete('/dashboard/desfazer-importe/{id}', 'DeleteImportController@destroy')->middleware('auth');
});

我的看法

div class="modal-body">    
     <h5>Deseja realmente desfazer esta importação?</h5>
     <input type="hidden" value="<?php $portal_id ?>" id="portal_id">  
</div>

<div class="modal-footer">
       <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
       <button type="button" class="btn btn-primary" id="delete" data-token="">Desfazer</button>
</div>  

我通过隐藏的输入获取 id

在 Ajax 中我有以下代码

function deleteImport()
{
   $('#delete').click(function() {
   let porta_id = $('#portal_id').val() 
   $(this).prop("disabled",true);

   $.ajax({
        type: 'DELETE',
        url: '/dashboard/desfazer-importe',       
        data: {
            "id": porta_id,  
        }, 
        success: function(response) {
            console.log(response)
        },
        error: function(error) {
            console.log(error)
        }
      })
   })
 }

它可能在不使用表单操作的情况下删除项目?我发送时收到此消息

message: "CSRF token mismatch."

标签: phplaravel

解决方案


您必须将 csrf 令牌添加到您的请求中:https ://laravel.com/docs/7.x/csrf#csrf-x-csrf-token

看起来你还有另一个问题。您必须将您的项目 ID 添加到 url。/dashboard/desfazer-importe/{id}


推荐阅读