变量不会从 AJAX 函数返回 [英] Variable doesn't get returned from AJAX function
问题描述
随着我的框架的增长,我决定将其拆分为多个文件,而不是将其留在主设计文件中.但是,通过这样做,函数的返回不会返回任何值.
As my framework grows i decided to split it into files, instead of leaving it in the main design file. However by doing that the return of a function doesn't return any value.
数据不为空 - 如果我提醒 js 文件中的值,它们就在那里!
data isn't empty - if i alert the values in the js file they are there!
功能:
1st .js 文件中的函数(在执行前包含)
1st the function in .js file (is included before the execution)
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;
}
}
});
}
};
所以,这里是执行部分:
So and here is the execution part:
var test = get_data(data, destination);
notice(test);
并且测试是空的......我已经尝试了不同的写作方式,但我想我误解了js的可能性?
and test is empty... I already tried different ways for writing but I guess i missunderstood the possibilities of js?
推荐答案
你不能这样做:由于调用是异步的,get_data 函数无法返回 ajax 调用的结果.
You can't do that : as the call is asynchronous, the get_data function can't return the result of the ajax call.
您应该做的是向 get_data 函数提供回调并在回调中处理结果.
What you should do is provide a callback to the get_data function and handle the result in the callback.
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);
}
}
});
}
};
然后这样称呼它:
get_data(data, destination, function(test){
notice(test);
});
这篇关于变量不会从 AJAX 函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!