变量不会从AJAX函数返回

Iva*_*ich 10 javascript ajax jquery

随着我的框架的增长,我决定将其拆分为文件,而不是将其留在主设计文件中.但是,通过这样做,函数的返回不会返回任何值.

数据不为空 - 如果我警告js文件中的值,它们就在那里!

功能:

第一个.js文件中的函数(在执行之前包含)

             var lock_get = 0;
             function get_data(data, destination) 
             {

                if (lock_get == 0)
                {
                    lock_get = 1;
                    $.ajax({
                        type: "POST",
                        url: destination,
                        async: true,
                        data: data,
                        success: function(data) 
                        {
                            lock_get = 0;
                            if (data)
                            {
                                return data;
                            }
                        }
                    });
                }
             };
Run Code Online (Sandbox Code Playgroud)

所以这里是执行部分:

    var test = get_data(data, destination);
    notice(test);
Run Code Online (Sandbox Code Playgroud)

并且测试是空的...我已经尝试了不同的写作方式,但我想我错过了js的可能性?

Den*_*ret 10

你不能那样做:因为调用是异步的,get_data函数不能返回ajax调用的结果.

你应该做的是提供对get_data函数的回调并在回调中处理结果.

function get_data(data, destination, callback) 
         {

            if (lock_get == 0)
            {
                lock_get = 1;
                $.ajax({
                    type: "POST",
                    url: destination,
                    async: true,
                    data: data,
                    success: function(data) 
                    {
                        lock_get = 0;
                        if (data && callback)
                        {
                            callback(data);
                        }
                    }
                });
            }
         };
Run Code Online (Sandbox Code Playgroud)

并称之为:

get_data(data, destination, function(test){
   notice(test);
});
Run Code Online (Sandbox Code Playgroud)