`
var data是我的jquery变量,我想在其中添加jsonData.image_name字符串文本。但要继续说undefined下去。
var data
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; }
您无法从异步调用返回数据,则应该在成功回调函数中进行操作。由于在数据到达时会调用回调,但是您要在此之前返回数据,所以您会得到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)