我有这个HTML:

<div class="d-inline-flex">
    <img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
    <input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>


$avatar的值:

$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
    $avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
    $avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}


以及向我的文件发送ajax调用以处理文件上传请求的脚本:

$(function () {
    var form;
    $('#uploadAvatar').change(function (event) {
        form = new FormData();
        form.append('uploadedAvatar', event.target.files[0]);
    });
    $("#uploadAvatar").change(function() {
      $("#loadingIMG").show();
      var imgEditATTR = $("div.imgP").next().attr("src");
      var imgEdit = $("div.imgP").next();
      $.ajax({
          url: 'http://example/test/profileForm.php',
          data: form,
          processData: false,
          contentType: false,
          type: 'POST',
          success: function (data) {
            $("#loadingIMG").hide();
            $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
          }
      });
    });
});


我试图强制浏览器在成功Ajax调用$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());时重新加载img,但selector varimgEdit中的imgEditATTR无法正常工作:

console.log(imgEdit);结果:w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit);结果:undefined;

为什么会发生,以及如何解决?

我知道有很多关于重新加载img的问题,但是在这些问题上,没有一种不知道文件名就可以重新加载图像的方法。我检查了很多问题,这就是Answears所说的:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());


就我而言,我不知道文件名,因为它是在profileForm.phpmt_rand()上随机生成的:

$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg

move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);

最佳答案

您可以返回文件名以响应您的AJAX请求,并在成功块中使用它来更新img标签的src属性

因此,您的profileForm.php看起来像



 $ext = explode('.',$_FILES['uploadedIMG']['name']);
    $extension = $ext[1];
    $newname = mt_rand(10000, 10000000).'_'.time();
    $folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
    //example of the result: 9081341_1546973622.jpg
    move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
    echo $newname // you can also send a JSON object here
    // this can be either echo or return depending on how you call the function




您的AJAX代码将如下所示



$.ajax({
      url: 'http://example/test/profileForm.php',
      data: form,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function (data) {
        $("#loadingIMG").hide();
        $(imgEdit).attr('src', data);
      }
  });

10-04 22:56