【问题标题】:How to get image from DB & preview it in edit form using ajax in laravel?如何从数据库中获取图像并在 laravel 中使用 ajax 以编辑形式预览它?
【发布时间】:2021-05-10 19:02:16
【问题描述】:

我正在尝试在 laravel 中使用 ajax 从数据库中获取数据。我得到了所有数据并将其成功加载到编辑表单中,除了图像。我从数据库中获取了图像,但无法在编辑表单上预览。

这是我的 ajax 调用

         function editProduct(id, category_id) {
          $.ajax({
            url: "{{ url('admin/products/edit/') }}/" + id,
            type: "GET",
            contentType: false,
            cache: false,
            processData: false,
            dataType: "json",

            success: function(response) {
                $("#edit-modal").modal("toggle");
                $(".id").val(response.id);
                $("#edit_name").val(response.name);
                $("#edit_category").val(category_id);
                $("#edi_image").val();   <---What to do here?  --->

            }
        });


    }

这是我的控制器代码

public function edit($id) {
    $product = FoodItem::findOrFail($id);
    return response()->json($product);
}

我想在这里加载图片

<img src='' id="edit_image" width="180px;" height="120" class="mt-2">
   <p>Old image</p>

谁能告诉我该怎么做?

【问题讨论】:

    标签: php jquery mysql ajax laravel


    【解决方案1】:

    我希望您将图像路径存储在数据库中,并将图像存储在公共资产中。如果是这种情况,那么只需使用 jQuery 更新图像 src

    $("#edi_image").attr('src','images/'+response.image); // change the path to your image
    

    【讨论】:

    • 谢谢,伙计!它奏效了。如果我选择新图像,那么如何在上传数据库之前将其加载到 jquery 中的旧图像位置?
    • 您可以在元素上使用 onchange 方法:例如
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2017-05-08
    • 2014-06-04
    • 2020-11-11
    • 2019-11-05
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多