无法解析并将ajax字符串返回到jquery变量

时间:2015-07-11 18:30:30

标签: javascript jquery ajax asynchronous callback

var data是我的jquery变量,我想在其中添加jsonData.image_name字符串文本。但是当它通过时继续说undefined

function SaveAndGetImageName() {
    var data = "";
    var formData = new FormData();
    formData.append('btn_Browse', $('#btn_Browse')[0].files[0]);
    $.ajax({
        url: '../Gem/SaveProfilePic',
        type: 'POST',
        dataType: 'json',
        cache: false,
        async: true,
        contentType: false,
        processData: false,
        data: formData,
        success: function (jsonData) {
            data = jsonData.image_name;
        }
    });

    return data;
}

1 个答案:

答案 0 :(得分:3)

你无法从异步调用返回数据,你应该在成功回调函数中进行操作。当数据到达时调用回调,但在此之前返回数据,因此您将获得undefined

function SaveAndGetImageName(processImageNameCallback) {
    var data = "";
    var formData = new FormData();
    formData.append('btn_Browse', $('#btn_Browse')[0].files[0]);
    $.ajax({
        url: '../Gem/SaveProfilePic',
        type: 'POST',
        dataType: 'json',
        cache: false,
        async: true,
        contentType: false,
        processData: false,
        data: formData,
        success: function (jsonData) {
            data = jsonData.image_name;
            processImageNameCallback(data);
        }
    });

    return data;
}

function processImageName(imageName){
   // do stuff with image name
   alert(imageName);
}

SaveAndGetImageName(processImageName)