使用 javascript 发布更改图像 src

Issue changing image src with javascript

我正在尝试根据 javascript 中的变量更改图像 SRC

我有以下模态:

<div class="modal-body">
    <img src="https://www.w3schools.com/js/landscape.jpg" alt="image" width="400" name="image_modal" id="image_modal">
    <div class="form-group">
        <label>Image Name</label>
        <input type="text" name="image_name" id="image_name" class="form-control" />
    </div>
    <div class="form-group">
        <label>Image Description</label>
        <input type="text" name="image_description" id="image_description" class="form-control" />
    </div>
    <div class="form-group">
        <label>Path</label>
        <input type="text" name="path" id="path" class="form-control" />
    </div>  
</div>
<div class="modal-footer">
    <input type="hidden" name="image_id" id="image_id" value="" />
    <input type="submit" name="submit" class="btn btn-info" value="Edit" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>

然后我尝试更改 JS 中的初始虚拟 SRC

...
$.ajax({
   url:"edit.php",
   method:"post",
   data:{image_id:image_id},
   dataType:"json",
   success:function(data)
   {
    $('#imageModal').modal('show');
    $('#image_id').val(image_id);
    $('#image_name').val(data.image_name);
    $('#path').val(data.path);
    $('#image_description').val(data.image_description);
    document.getElementById("image_modal").src = val(data.path);
   }
});

我正在检查 src URL 是否正确,方法是在模态 (data.path) 中显示它并正确输出。

但是当尝试使用 document.getElementById("image_modal").src = val(data.path); 更改 src 时,没有显示图像,就像变量没有被正确解释一样。

您的问题在这里:val(data.path);

除非您已经定义,否则 val() 是未定义的。你应该能够只使用 data.path,假设它是你之后的字符串。

改用这个

document.getElementById("image_modal").src = data.path;