[英]Accessing variable from callback using AJAX in jQuery
Code explains all: 代码说明了所有内容:
//
// … code ...
//
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
var my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
How do I get access to my_data
outside of the AJAX call? 我如何在AJAX调用之外访问my_data
? I've read that maybe a closure is needed? 我读过,也许需要关闭吗? I can't find any examples that do want I want though. 我找不到任何想要的示例。
Many thanks. 非常感谢。
Ajax is async
call and success may be fired after console.log, you can call a function from success and pass data to it. Ajax是async
调用,在console.log之后可能会触发成功,您可以成功调用一个函数并将数据传递给它。
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
yourFun(data);
}
});
function yourFun(data)
{
}
To giving function instead of success. 给人机能而不是成功。
$.ajax({
dataType: "json",
url: "foo",
success: yourFun
});
function yourFun(data)
{
}
Generally speaking, you don't. 一般来说,您不需要。 AJAX calls are asynchronous so there's no guarantee of a value immediately after the jQuery.ajax()
function has executed; AJAX调用是异步的,因此在执行jQuery.ajax()
函数后无法立即保证值; you need to wait until the AJAX call has completed, and the success
callback has executed, before you attempt to use that variable. 在尝试使用该变量之前,您需要等待AJAX调用完成并且success
回调已执行。
The easiest approach is to just use that value inside the success
callback. 最简单的方法是只使用内部的价值success
的回调。 If you really need it to be available outside then make it a variable that's visible to all of your code (not necessarily global, depending on how your code is structured), and check that it has a value before you attempt to use it in any other functions. 如果您确实需要在外部使用它,请将其设置为所有代码可见的变量(不一定是全局变量,具体取决于代码的结构),并在尝试在任何代码中使用它之前检查它是否具有值其他功能。
Define my_data
as global as below, 如下定义my_data
为全局,
var my_data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
Declare my_data variable globally.. 全局声明my_data变量。
var my_data = data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
Use my_data
as gloabl
variable to access data outside of ajax. 使用my_data
作为gloabl
变量来访问ajax之外的数据。
var my_data = '';
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
console.log(my_data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.