变量不从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!
功能:
1日在.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);
和测试是空的......我已经尝试过不同的方式写作,但我想我missunderstood 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屋!