小编典典

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

ajax

`

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;
}

阅读 280

收藏
2020-07-26

共1个答案

小编典典

您无法从异步调用返回数据,则应该在成功回调函数中进行操作。由于在数据到达时会调用回调,但是您要在此之前返回数据,所以您会得到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)
2020-07-26