通过回调更新全局变量

时间:2015-12-30 06:44:10

标签: javascript ajax

我有以下功能

   var urls = '';
    handleFiles(f,function(url){
        urls = urls + url + ',';
        console.log("urls is " + urls);
    });

上传并更新我的网址后,我收到了网址。但我的Urls永远不会更新,它会显示上传的最后一个文件的网址。

更新1 这是我现在的完整代码。

var urls = '';
document.getElementById('question-file-selector').addEventListener('change',handleFileSelect,false);
    function handleFileSelect(evt){
        var files = evt.target.files; //File list object
            // Loop through file list, render image files as thumbnails
        for (var i = 0,f;f = files[i];i++){


        handleFiles(f,function(url){
                urls = urls + url + ',';
                console.log("urls is " + urls);
                });
        // Only process image files
        if (!f.type.match('image.*')){
            $('#list').append('<img class="file-thumb" src="/static/download168.png"/>');
            continue;
        }
        var reader = new FileReader();

        //Closure to capture file information
        reader.onload = (function(theFile){
                return function(e){
                    //Render thumbnail
                    $('#list').append('<img class="thumb" src="'+e.target.result+'" title="'+escape(theFile.name)+'"/>'); 
                    };
                    })(f);
        reader.readAsDataURL(f);
    }
    }

console.log("Url is",urls);`   

和我的ajax功能

    //Code for Image upload

// Custom jQuery xhr instance to support our progress bar.

var xhr_with_progress = function() {
     var xhr = new XMLHttpRequest();
     xhr.upload.addEventListener("progress",
         function(evt) {
             if (!evt.lengthComputable) return;
             var percentComplete = evt.loaded / evt.total;
             $("#progress-bar div.progress-bar").css('width', String(100*percentComplete) + "%");
         }, false);
     return xhr;
 };





$.support.cors = true;//For cross origin transfer

//Event listners to avoid default drag and drop reaction of browser
window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);
window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
},false);



function handleFiles(file,callback){

            var filename = file.name;
            $.ajax({
                type:'GET',
                data:{"filename":file.name, "FileType":"question_file"},
                url:'/dashboard/generateuploadurl/',
                contentType:"application/json",
                dataType:"json",
                async:false,
                success: function(data){ 
                    if(data.UploadUrl){
                      console.log("upload url successfully created for " + file.name + " file");
                        console.log(data.UploadUrl);
                        handleUpload(data.UploadUrl, file, data.Filename,callback);

                    }
                },
                error: function(data){ 
                    console.log("error occured while creating upload url for " + file.name + ' file');
                    console.log(data);
                },
            });
        }           
function handleUpload(UploadUrl, file, Filename,callback){
    $.ajax({
        xhr:xhr_with_progress,
        url:UploadUrl,
        type:'PUT',
        data:file,
        cache:false,
        contentType:false,
        processData:false,
        success: function(data){
            console.log('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
            callback('https://7c.ssl.cf6.rackcdn.com/'+ Filename);
        },
        error: function(data){ 
            alert("error occured while uploading " + file.name );
            console.log(data);
        },
    }); 
}

1 个答案:

答案 0 :(得分:0)

协调多个异步操作是使用promises等工具最好地解决的工作。所以,从长远来看,我建议你阅读有关承诺以及如何使用它们的信息。

没有承诺,这里有一种蛮力方式,您可以通过使用计数器知道何时完成最后一次异步操作然后使用handleFiles()来完成所有urls操作变量INSIDE最后一次回调或从那里调用一个函数并将urls变量传递给该函数:

document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    var urls = "";
    // Loop through file list, render image files as thumbnails
    var doneCnt = 0;
    for (var i = 0, f; f = files[i]; i++) {
        handleFiles(f, function (url) {
            urls = urls + url + ',';
            console.log("urls is " + urls);
            ++doneCnt;
            if (doneCnt === files.length) {
                // The last handleFiles async operation is now done
                // final value is in urls variable here
                // you can use it here and ONLY here

                // Note: this code here will get executed LONG after the
                // handleFileSelect() function has already finished executing
            }
        });
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('<img class="file-thumb" src="/static/download168.png"/>');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>');
            };
        })(f);
        reader.readAsDataURL(f);
    }
}

// You can't use the urls variable here.  It won't be set yet.

哦~~。请从您的ajax电话中删除async: false。由于各种原因,编码很可怕。

这是一个使用jQuery内置的promise的版本:

document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false);

function handleFileSelect(evt) {
    var files = evt.target.files; //File list object
    // Loop through file list, render image files as thumbnails
    var promises = [];
    for (var i = 0, f; f = files[i]; i++) {
        promises.push(handleFiles(f));
        // Only process image files
        if (!f.type.match('image.*')) {
            $('#list').append('<img class="file-thumb" src="/static/download168.png"/>');
            continue;
        }
        var reader = new FileReader();
        //Closure to capture file information
        reader.onload = (function (theFile) {
            return function (e) {
                //Render thumbnail
                $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>');
            };
        })(f);
        reader.readAsDataURL(f);
    }
    $.when.apply($, promises).then(function() {
        var results = Array.prototype.slice.call(arguments);
        // all handleFiles() operations are complete here
        // results array contains list of URLs (some could be empty if there were errors)
    });
}

function handleFiles(file) {
    var filename = file.name;
    return $.ajax({
        type: 'GET',
        data: {
            "filename": file.name,
            "FileType": "question_file"
        },
        url: '/dashboard/generateuploadurl/',
        contentType: "application/json",
        dataType: "json"
    }).then(function(data) {
        if (data.UploadUrl) {
            console.log("upload url successfully created for " + file.name + " file");
            console.log(data.UploadUrl);
            return handleUpload(data.UploadUrl, file, data.Filename);
        }
    }, function(err) {
        console.log("error occured while creating upload url for " + file.name + ' file');
        console.log(err);
        // allow operation to continue upon error
    });
}

function handleUpload(UploadUrl, file, Filename) {
    return $.ajax({
        xhr: xhr_with_progress,
        url: UploadUrl,
        type: 'PUT',
        data: file,
        cache: false,
        contentType: false,
        processData: false
    }).then(function(data) {
        console.log('https://7c.ssl.cf6.rackcdn.com/' + Filename);
        return 'https://7c.ssl.cf6.rackcdn.com/' + Filename;
    }, function(err) {
        console.log("error occured while uploading " + file.name);
        console.log(err);
        // allow operation to continue upon error
    });
}

由于我无法运行此代码进行测试,因此可能存在错误或两个错误,但您应该能够调试这些错误或告诉我们错误发生的位置,我们可以帮助您调试它。从概念上讲,这些是如何解决协调多个异步操作的这些类型的问题。