使用变量的Ajax回调函数外 [英] Using variable outside of ajax callback function
问题描述
什么是最好的一个回调函数外使用全局变量?
VAR图标;
$(函数(){
$获得(data.xml的',功能(XML){
图标= xml.documentElement.getElementsByTagName(图标);
//这个输出值
执行console.log(图标);
});
//这是空
//这怎么可能保持高于设定值?
执行console.log(图标);
});
您提供的code是完全有效的 - 而且,事实上,图标
确实的维持它的价值。这个问题,可能的是,的get()
异步运行 - 只调用匿名函数的在的data.xml中
已完全从服务器加载。因此,执行的现实世界中的序列看起来是这样的:
- 呼叫
的get(data.xml的',功能(XML){...})
(开始加载data.xml中) - 呼叫
的console.log(图标)
(图标
仍是空在这一点) - (data.xml中完成加载)的现在的匿名函数被调用,它分配值图标:
图标= xml.documentElement.getElementsByTagName(图标)
。
如果你想要做一些与图标
的值,在的了data.xml中被取出,那么你会需要做的在的匿名回调函数。像这样的:
VAR图标;
$(函数(){
$获得(data.xml的',功能(XML){
图标= xml.documentElement.getElementsByTagName(图标);
执行console.log(图标);
});
});
祝你好运!
请注意:您仍然可以使用图标
从code即的之外的匿名函数,但你需要等待访问它,直到的在的匿名功能已运行。要做到这一点,最好的办法是把相关的code到自己的函数,然后调用该函数的回调函数中:
VAR图标;
$(函数(){
$获得(data.xml的',功能(XML){
图标= xml.documentElement.getElementsByTagName(图标);
loadIcon();
});
功能loadIcon(){
执行console.log(图标);
// ...做任何你需要做的图标点击这里
}
});
What is the best to use global variables outside of a callback function?
var icon;
$(function(){
$.get('data.xml', function(xml){
icon = xml.documentElement.getElementsByTagName("icon");
//this outputs a value
console.log(icon);
});
//this is null
//How can this maintain the value set above?
console.log(icon);
});
The code you have provided is perfectly valid -- and, in fact, icon
does "maintain" it's value. The problem, likely, is that get()
runs asynchronously -- only calling the anonymous function after 'data.xml'
has been fully loaded from the server. So the real-world sequence of execution looks something like this:
- call
get('data.xml', function(xml){...})
(starts loading data.xml) - call
console.log(icon)
(icon
is still null at this point) - (data.xml finished loading) now the anonymous function is called, which assigns the value to icon:
icon = xml.documentElement.getElementsByTagName("icon")
.
If you want to do something with the value of icon
, after the 'data.xml' has been fetched, then you'll need to do it inside the anonymous callback function. Like this:
var icon;
$(function(){
$.get('data.xml', function(xml){
icon = xml.documentElement.getElementsByTagName("icon");
console.log(icon);
});
});
good luck!
Note: you can still use icon
from code that is outside the anonymous function, but you'll need to wait to access it, until after the anonymous function has been run. The best way to do this is to put the dependent code into its own function, and then call that function from within the callback function:
var icon;
$(function(){
$.get('data.xml', function(xml){
icon = xml.documentElement.getElementsByTagName("icon");
loadIcon();
});
function loadIcon() {
console.log(icon);
// ... do whatever you need to do with icon here
}
});
这篇关于使用变量的Ajax回调函数外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!