You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript调用路由在Laravel 5中删除数据库数据?

没问题,我来一步步帮你实现这个删除功能,结合你现有的模态框,咱们从路由、控制器到前端JS一步步来:

Laravel 5 实现数据库数据删除(结合模态框与JavaScript)

1. 完善你的模态框HTML

你提供的模态框代码不完整,我帮你补充必要的内容,包括存储待删除ID的隐藏域和确认按钮:

<div class="modal fade" id="deletePub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title" id="modalPublicationTitle">Confirm Publication Delete</h6>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        你确定要删除这条发布内容吗?此操作不可撤销。
        <!-- 隐藏域存储待删除的记录ID -->
        <input type="hidden" id="deletePublicationId">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
      </div>
    </div>
  </div>
</div>

2. 配置Laravel删除路由

在routes/web.php中定义一个DELETE方法的路由(符合RESTful规范),指向控制器的删除方法:

// 替换PublicationController为你实际的控制器名称,{publication}是路由模型绑定的参数
Route::delete('/publications/{publication}', 'PublicationController@destroy')->name('publications.destroy');

3. 编写控制器的删除逻辑

在app/Http/Controllers/PublicationController.php中实现destroy方法,利用Laravel的路由模型绑定自动获取待删除的记录:

use App\Publication; // 替换为你的模型类

public function destroy(Publication $publication)
{
    // 执行删除操作
    $publication->delete();
    
    // 返回JSON响应给前端
    return response()->json([
        'success' => true,
        'message' => '发布内容已成功删除'
    ]);
}

4. 编写JavaScript调用逻辑

这里分两步:一是点击页面上的删除按钮时传递ID到模态框;二是点击确认按钮时发送删除请求。

// 获取Laravel自动生成的CSRF令牌(确保页面头部有<meta name="csrf-token" content="{{ csrf_token() }}">)
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

// 绑定页面中删除按钮的点击事件(假设删除按钮有类名.btn-delete,且data-id存储记录ID)
document.querySelectorAll('.btn-delete').forEach(btn => {
    btn.addEventListener('click', function() {
        const pubId = this.getAttribute('data-id');
        // 将ID存入模态框的隐藏域
        document.getElementById('deletePublicationId').value = pubId;
        // 打开模态框
        $('#deletePub').modal('show');
    });
});

// 绑定模态框确认删除按钮的点击事件
document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    const pubId = document.getElementById('deletePublicationId').value;
    
    // 用axios发送DELETE请求(如果项目没引入axios,也可以用原生fetch)
    axios.delete(`/publications/${pubId}`, {
        headers: {
            'X-CSRF-TOKEN': csrfToken
        }
    })
    .then(response => {
        // 成功后的操作:关闭模态框、提示用户、移除页面上对应的记录元素
        alert(response.data.message);
        $('#deletePub').modal('hide');
        document.querySelector(`.publication-item[data-id="${pubId}"]`).remove();
    })
    .catch(error => {
        // 错误处理
        alert('删除失败,请稍后重试');
        console.error(error);
    });
});

替代方案:用原生fetch实现请求

如果你的项目没有引入axios,可以用原生fetch替换:

fetch(`/publications/${pubId}`, {
    method: 'DELETE',
    headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json'
    }
})
.then(res => res.json())
.then(data => {
    // 成功处理逻辑和上面一致
})
.catch(err => {
    alert('删除失败,请稍后重试');
    console.error(err);
});

注意事项

  • 确保页面头部存在CSRF令牌的meta标签,Laravel默认会在布局文件中生成:
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
  • 如果你用的是Bootstrap模态框,要确保已经引入了jQuery和Bootstrap的JS文件。

内容的提问来源于stack exchange,提问作者Zoythrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:16:10