无法解析并将ajax字符串返回到jquery变量 [英] Can't parse and return ajax string to jquery variable

查看:20
本文介绍了无法解析并将ajax字符串返回到jquery变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

异步调用无法返回数据,需要在成功回调函数中进行操作.由于在数据到达时调用回调,但您在此之前返回数据,因此您将获得 undefined.

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)

这篇关于无法解析并将ajax字符串返回到jquery变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆