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;
}
答案 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)