简体   繁体   English

从javascript中的另一个函数知道ajax调用的结果

[英]Know the result of a ajax call from another function in javascript

I have a function uploadFunction that upload file on my server through Rest web service called with JQuery ajax. 我有一个函数uploadFunction,它通过使用JQuery ajax调用的Rest Web服务在服务器上上传文件。 I use this method also for another function and I need to know the result of web service call to create or less one row with the name of the file that has been uploaded. 我还将这种方法用于另一种功能,并且我需要知道Web服务调用的结果,以创建或上载少于上载文件名的一行。
The actual approach with the variable doesn't work, is there a way to know if the file is correctly uploaded? 使用变量的实际方法不起作用,是否有办法知道文件是否正确上传? I tried with async: false (because I anyway wait the upload) but my waiting modal appears and the end of upload and not immediately. 我尝试了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);
    });
}

My function that call uploadFunction is this: 我调用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 = '';
                    }
                }

            });
});

Use promises. 用诺言。 Just return the ajax promise (its return value) from uploadResult() and add the followup code inside an .then or .done call: 刚刚返回从AJAX承诺(它的返回值) uploadResult()并添加一个内部的后续代码.then.done电话:

eg 例如

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

and use like this: 并像这样使用:

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

Never use async: false . 永远不要使用async: false It blocks the browser from any other processing. 它将阻止浏览器进行任何其他处理。 Always work with async operations. 始终使用异步操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM