javascript - 了解 JavaScript 中另一个函数的 ajax 调用结果

标签 javascript jquery ajax asynchronous

我有一个函数 uploadFunction,它通过使用 JQuery ajax 调用的 Rest Web 服务将文件上传到我的服务器上。 我也将此方法用于另一个函数,并且我需要知道 Web 服务调用的结果,以创建或少于一行包含已上传文件的名称。
使用变量的实际方法不起作用,有没有办法知道文件是否正确上传? 我尝试使用 async: false (因为无论如何我都会等待上传),但我的等待模式出现并且上传结束,而不是立即结束。

function uploadFunction(fileType){
//CSRF attribute for spring security
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

var formData = new FormData();
var fileControl = document.getElementById(fileType);
var length = fileControl.files.length;
for(var i = 0; i< length; i++){ 
    formData.append('file[]',fileControl.files[i]); 
} 
formData.append('idFleet', selectedFleet);
formData.append('idCar', $("#selectedCar").val());
if(fileType!='dat')
    formData.append('initialKm', 0);
else
    formData.append('initialKm', $("#initialKm").val());
jQuery.ajax({
    url : 'upload',
    type: 'POST',
    contentType: false,
    processData: false,
    data:formData,
    beforeSend:function(xhr) {
        xhr.setRequestHeader(header, token);
        waitingModal.showPleaseWait();
    },  
    success: function(data,status,xhr){
        //No exception occurred
        if (data.status){   
            //Also the field are right(for e.g. form value)
            if(data.success){
                //Store information if file is datatable
                if (fileType=='datatable')
                    $("#datatablePath").val(data.result[0]);
                notifyMessage(fileType + " has been uploaded!", 'success');
                uploadResult=true;
            }
            else{
                //code if there are some error into form for example
            }
        } else {
            notifyMessage(data.result, 'error');
            $('#acquisitionWizard').bootstrapWizard('show',2);//show
            uploadResult=false;
        }
    },
    error: function(xhr,status,e){
        window.location.href = "/ATS/500";
    }
}).complete(function() {
    //add timeout because otherwise user could see a too fast waiting modal
    setTimeout(function(){
        waitingModal.hidePleaseWait();
    }, 1000);
    });
}

我调用uploadFunction的函数是这样的:

$(function() {
    $("#addDatButton").click(
            function() {
                var fileControl = document.getElementById('dat');
                if (fileControl.files.length!=0 && $('#initialKm').val().length == 0){  
                    notifyMessage("You have to add initial Km!", 'info');
                }else if (fileControl.files.length==0 && $('#initialKm').val().length != 0){    
                    notifyMessage("You have to add dat file!", 'info');
                }else if (fileControl.files.length==0 && $('#initialKm').val().length == 0){    
                    notifyMessage("You have to add dat file and initial Km!", 'info');
                }else{
                    uploadFunction('dat');
                    if (uploadResult){
                        datUpload=true;
                        var fileName=document.getElementById('datName').value;
                        var fileUploadHTML='<div class="row"> <div class="col-xs-4"><div class="form-group has-success"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-upload" style="color: green"></i></span> <input type="text" class="form-control" readonly="readonly" placeholder="'+fileName+'"></div></div></div><div>';
                        $("#fileUploadSuccess").append( fileUploadHTML );
                        document.getElementById("initialKm").value = '';
                        document.getElementById("dat").value = '';
                        document.getElementById("datName").value = '';
                    }
                }

            });
});

最佳答案

使用 promise 。只需从 uploadResult() 返回 ajax Promise(其返回值),并在 .then.done 调用中添加后续代码:

例如

function uploadFunction(fileType){
    [snip]
    return jQuery.ajax({

并像这样使用:

uploadFunction('dat').then(function(uploadResult){
     if (uploadResult){
         [snip]
     }
});

切勿使用async: false。它阻止浏览器进行任何其他处理。始终使用异步操作。

关于javascript - 了解 JavaScript 中另一个函数的 ajax 调用结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903170/

相关文章:

JQuery 悬停覆盖问题

javascript - 一次点击完全完成后停止onclick事件监听所有 Action

ajax - 在 iPhone 和 Android 上通过 Phonegap 使用 session 变量和 cookie

javascript - 什么是 char 的最佳替代品?

javascript - 从 Angular JS ng-options/ng-repeat 中删除重复项

javascript - 重构 JSON 数组

javascript - 将 bootstrap 多选值拆分为多个变量

jQuery : how to intersect two data-attribute selector queries

Javascript/AJAX - 从表单获取参数数组

javascript - MongoDB 中的reduce 函数出现奇怪的数值错误