首页 > 解决方案 > 如何使用 POST 方法将 jquery 中的数据传递到 laravel 控制器

问题描述

使用方法 post 将数据从 jquery ajax 传递到控制器时,我遇到了问题。我无法删除 product_tool 表。它给了我 ajax 中的回调错误。不是回调成功。

并且控制台中没有错误,但它给了我错误回调,这意味着有错误。同样,当我调试并查看网络(在 Firefox 上)时,状态为 500。

抱歉我来晚了编辑它。

我已经尝试了堆栈溢出的每一个解决方案。没有任何效果。

这是我的 ajax 脚本:

var token = "{{csrf_token()}}";
$.ajax({
                method: 'POST',
                url: '{{ url("/deleteProductTool/$cari->id") }}',               
                data: {
                    id_tool : id,
                    _token : token
                 },
                success: function(){
                    $.get('{{ url("/showTools/$cari->id") }}'), function(data, status){
                    $('#tool').html(data);
                }
                },
                error : function(response){
                    alert(response+" Gagal");
                }
            });

这是我的路线:

Route::post('/deleteProductTool/{id}','ProductController@deleteProductTool');

这是我的控制器:

public function deleteProductTool(Request $request, $id){
        if (Request::ajax()) {
        $product = Product::findOrFail($id);
        if (empty($product)) {
            abort(404);
        }

        $tool = Tool::findOrFail($request->id_tool);
        if (empty($tool)) {
            abort(404);
        }

        $hapus = ProductTool::where([
            ['product_id', $product->id],
            ['tool_id', $tool->id],
        ])->delete();

        // return $hapus;   
        }else{
            abort(404);
        }

    }

标签: jqueryajaxlaravelrequest

解决方案


你在删除hapus时做错了。您的产品工具是持有集合的变量。试试看:

$hapus = ProductTool::where([
            ['product_id', $product->id],
            ['tool_id', $tool->id_tool],
        ])->delete();

推荐阅读