Ajax 请求减慢了函数的其余部分,如何修复

Ajax request slows down the rest of the function, how to fix?

本文关键字:余部 何修复 请求 函数 Ajax      更新时间:2023-09-26

我做了一些拖放功能来保存图像,我想看看我刚刚保存了哪些图像。问题是我不会等待 ajax 请求将该图像发送到服务器,我想要图像的即时预览。我编写了可以做到这一点的代码,但是当我向其添加 ajax 请求时,在 ajax 请求完成之前,我不会在我的 html 页面上看到此图像。但是,如果我评论这个 ajax 请求,图像会立即出现在 html 页面上。我怎样才能得到所有这些?阿贾克斯+即时预览。

这是我的代码,请随时询问我:

// initialise our dropzone and set ondrop event function 
var dropzone = document.getElementById('ta');
dropzone.ondrop = function(e){
   e.preventDefault();
   readfiles(e.dataTransfer.files);
};
// preview image that was added to dropzone
function previewImg(file) {
   var image = new Image();

   image.src = webkitURL.createObjectURL(file);// make url for image using webkitURL
   image.width = 550; // a fake resize
   document.getElementById('body').appendChild(image); // add image to element (for example to the body)
}    
function readfiles(files) {
   var formData = new FormData();
   for (var i = 0; i < files.length; i++) {
   previewImg(files[i]); // call for preview
   formData.append('file'+i, files[i]); // add file to form

   }
   formData.append('moreInfo','myValuableValue');// you can append additional string info
   // if we comment this request preview will appear instant
   // but if we not, preview will appear only after end of ajax request
   $.ajax({
    url: './file_handler.php',
    type: 'POST',
    data: formData,
    async: false,
    success: function (data) {
        console.log('done');
    },
    cache: false,
    contentType: false,
    processData: false
   });

}       

我想解决这个问题,但我不知道怎么做,我使用 jQuery $.ajax 请求。顺便说一下,控制台输出也会变慢,并在请求结束后立即显示所有输出。请给我指路。

在传递给 $.ajax 调用的设置中,设置 async: true