Can't parse and return ajax string to jquery v

2019-01-20 17:15发布

This question already has an answer here:

var data is my jquery variable, i want to add jsonData.image_name string text in to it. but keep saying undefined when it passes.

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条回答
太酷不给撩
2楼-- · 2019-01-20 17:54

you cant return data from Asynchronous calls, you should do the manipulation in the success callback function. As callbacks are called when the data is arrived, but you are returning the data before that so you are getting 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)
查看更多
登录 后发表回答