[英]Javascript Variable Not Changed Outside of Function Scope
I have the following function: 我有以下功能:
function loginStudent() {
var advisorKEY = "<dtml-var expr="py_get_alias()">";
var studentKEY = "<dtml-var SID>";
var URL = "py_logging_sessionOpen?AdvisorKEY=" + advisorKEY + "&StudentKEY=" + studentKEY;
key = "";
$j.get(URL, function(data) {
key = data;
});
alert(key);
}
The py_loggin_sessionOpen
is just a python script running on my server. py_loggin_sessionOpen
只是在我的服务器上运行的python脚本。
It returns a single string. 它返回一个字符串。 I need the response of that script to determine the next action.
我需要该脚本的响应来确定下一步操作。 The script returns the value perfectly, and I can easily check the value by putting an
alert
within the function(data)
in get
. 脚本完美地返回了值,我可以通过在
get
的function(data)
内放置alert
来轻松地检查值。
My main question is: how to get the key value to be changed outside the scope of function(data)? 我的主要问题是:如何获得要在功能(数据)范围之外更改的键值?
I assumed because I defined it externally it would act as a global variable. 我以为是因为我在外部定义了它,所以它将充当全局变量。 Moving it outside
loginStudent()
does not solve the problem either. 将其
loginStudent()
之外也不能解决问题。
Any ideas? 有任何想法吗?
$j.get()
is going to be an asynchronous call. $j.get()
将是一个异步调用。 That means it fires, and the rest of the execution continues. 这意味着它将触发,其余的执行将继续。 Anything that relies on that call needs to be done in the callback, like so:
任何依赖于该调用的操作都需要在回调中完成,如下所示:
$j.get(URL, function(data) {
key = data;
alert(key);
} );
If everything else is good, you'll see the value you expect. 如果其他一切都很好,您将看到期望的价值。
The problem with your code is that $j.get
executes asynchronously. 您的代码的问题在于
$j.get
是异步执行的。 That's the reason you pass a callback to it. 这就是您将回调传递给它的原因。
If you wish to write asynchronous code synchronously then you should read this answer: https://stackoverflow.com/a/14809354/783743 如果您希望同步编写异步代码,则应阅读以下答案: https : //stackoverflow.com/a/14809354/783743
Edit: It seems that you have created a global variable called key
by not declaring it with var
. 编辑:似乎您通过不使用
var
声明了一个名为key
的全局变量。 Hence it should be visible in other functions as long as they are called after the callback. 因此,只要在回调之后调用它们,它就应该在其他函数中可见。
Would you care to provide us these other functions? 您愿意为我们提供这些其他功能吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.