首页 > 解决方案 > 如何在 PHP 中 ajax 成功后重置图像文件预览?

问题描述

我正在使用 ajax 和 PHP PDO 插入数据库。我有两个领域。1.消息和2.图像。我有一个问题,图像预览(浏览文件)在插入和显示数据后没有重置(在 ajax 成功后)。ajax 成功后,消息 Textarea 值正在重置,但不是图像预览。

阿贾克斯代码:

$(document).on("click", "#save", function (e) {
    e.preventDefault();
    var message = $("#message").val();
    var form_data = new FormData();
    form_data.append('message', message)
    var property = document.getElementById('photo').files;
    property = property[0];
    if (property) {
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();
        form_data.append("file", property);
    }

    $.ajax({
        type: "POST",
        url: "insert_posts.php",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function (data) {
            //Insert data before the message wrap div
            $(data).insertBefore(".message-wrap:first");
            //Clear the textarea message
            $("#message").val("");

            $("#form")[0].reset();
            $('#preview').attr('src', "#");
            $("#photo").val("");


        }
    });
});

我正在使用 JS 在更改时预览图像(浏览图像并查看预览)

<script type="text/javascript">
   //Image Preview Function
    $("#uploadTrigger").click(function(){
       $("#photo").click();
    });
          function readURL(input) {
              if (input.files && input.files[0]) {
                  var reader = new FileReader();
   
                  reader.onload = function (e) {
                    $('#body-bottom').show();
                      $('#preview').attr('src', e.target.result);
                                $("#photo").val("");
                  }
   
                  reader.readAsDataURL(input.files[0]);
              }
          }
   
</script>

插入后消息值正在重置,但不是图像。我正在使用 HTML 代码行进行预览。

<div id="body-bottom"> 
   <img src="#"  id="preview"/> 
</div>

应该重置图像预览并且 type="file" 我正在使用类型文件代码:

<input type="file"  onchange="readURL(this);" style="display:none;" name="photo" id="photo">
<img src="assets/icon/icon1.png"></img><a href="#" id="uploadTrigger" name="post_image">Add Photo</a> 

图像预览未重置。如果我再次单击相同的图像插入。我想在ajax成功后重置图像。

标签: javascriptphpjqueryajax

解决方案


我已经解决了这个问题。只需在表单重置上方添加行

$("#photo").val(""); $("#form")[0].reset();

或者您可以在最后放置表单重置。如果要隐藏预览,请添加行 -

$('#body-bottom').hide();


推荐阅读