[英]How to use and reuse JS variables across functions
I have a situation where I need to initialize/assign variables from the results of a jQuery AJAX call, and then re-use those variables further on down the script: 我遇到一种情况,需要从jQuery AJAX调用的结果中初始化/分配变量,然后在脚本中进一步重复使用这些变量:
var shouldRedirect = ???
$.ajax({
url: 'http://example.com',
type: 'GET',
data: 'blah',
asynch: false,
timeout: 1800,
success: function(data) {
shouldRedirect = data.rows[0].redirectFlag
}
});
if(shouldRedirect)
window.location = "...";
Two issues I'm having: 我遇到两个问题:
redirectFlag
boolean, is data.rows[0].redirectFlag
the proper way of obtaining the value for my variable?; 假设结果JSON将包含一个redirectFlag
布尔值, data.rows[0].redirectFlag
是获取我的变量值的正确方法吗? and 和 shouldRedirect
to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")? 在启动AJAX之前,我应该如何初始化shouldRedirect
到什么(我该怎么说“创建变量,但不给它一个值!”)? Thanks in advance! 提前致谢!
You can declare uninitialized variables by simply doing the following: 您只需执行以下操作即可声明未初始化的变量:
var shouldRedirect;
If your logic requires it you can of course initialize it to false: 如果您的逻辑需要它,您当然可以将其初始化为false:
var shouldRedirect = false;
This might not be what you desire though. 但是,这可能不是您想要的。 You can check if a variable was initialized by strictly comparing it to undefined
: 您可以通过将变量与undefined
严格比较来检查变量是否已初始化:
if (shouldRedirect === undefined) // do something
Note though, that you must use the triple equal operator (aka strict equality) or your results will not be as expected. 但是请注意,您必须使用三重等于运算符(也称为严格相等),否则结果将与预期不符。 On the other side, an undefined variable will yield a falsy result. 另一方面,未定义的变量将产生错误的结果。 This means that when checking a variable with a simple if (shouldRedirect)
and the variable is undefined then it will yield false
, as if it was set to false. 这意味着,当使用简单的if (shouldRedirect)
检查变量并且该变量未定义时,它将产生false
,就像将其设置为false一样。 This is also true for a couple of other values in JavaScript, eg the empty string ""
or the value null
. 对于JavaScript中的其他两个值,例如空字符串""
或null
。 You can see a complete list of falsy values here . 您可以在此处查看虚假值的完整列表。 If you want to check explicitly for true or false and want to omit other falsy or truthy values, then you should check with triple equality, eg if (shouldRedirect === true)
. 如果要显式检查true或false并忽略其他虚假或真实值,则应使用三重相等进行检查,例如if (shouldRedirect === true)
。
Also, if data.rows[0].redirectFlag
is the correct way to access the value is highly dependend on how the data structure you receive from your AJAX call actually looks like. 另外,如果data.rows[0].redirectFlag
是访问值的正确方法,则高度取决于您从AJAX调用接收的数据结构的实际外观。 If it is something like the following it would be correct: 如果类似于以下内容,则将是正确的:
{ rows: [ {redirectFlag: true}, {redirectFlag: false} ] }
If your JSON looks like the following though 如果您的JSON如下所示
{ redirectFlag: false }
then you have to access redirectFlag simply with data.redirectFlag
. 那么您只需使用data.redirectFlag
即可访问redirectFlag。
What do I initialize shouldRedirect to before the AJAX is kicked off (how do I say "create a variable but don't give it a value yet!")? 在启动AJAX之前,我应该如何初始化shouldRedirect到什么(我该怎么说“创建变量,但不给它一个值!”)?
You could just do: var shouldRedirect;
您可以这样做: var shouldRedirect;
However, I would do var shouldRedirect = false;
但是,我会做var shouldRedirect = false;
to ensure shouldRedirect is not undefined 确保shouldRedirect没有未定义
Depends what you send back from the AJAX request. 取决于您从AJAX请求发回的内容。 Usually responses are in JSON so if you send a JSON object back with a value true then you could do: 通常,响应使用JSON格式,因此,如果您将JSON对象发送回值为true,则可以执行以下操作:
shouldRedirect = data.redirectFlag;
For part #1 to declare a variable with it having a value use: var shouldRedirect. 对于第1部分,要声明一个具有值的变量,请使用:var shouldRedirect。 This way you can just do a if (!shouldRedirect) {}. 这样,您就可以执行if(!shouldRedirect){}。
For part #2. 对于第2部分。 How to get the value from redirectFlag is based on the formation of the data returned from the ajax call. 如何从redirectFlag获取值基于ajax调用返回的数据的形式。 data... would be the starting point for you to get the value. 数据...将是您获得价值的起点。
As mentioned in the comments section, setting the shouldRedirect
flag isn't going to help as the if
statement that follows the $.ajax
request will be evaluated before the result is fetched from the server - this is a common problem faced in asynchronous code execution. 如注释部分所述,设置shouldRedirect
标志不会有帮助,因为在$.ajax
请求之后的if
语句将在从服务器获取结果之前进行评估-这是异步代码执行中常见的问题。 Although you can, in theory, force jQuery.ajax into syncronous mode via the sync
parameter, I wouldn't recommend doing so as it will lock up the browser UI whilst the request is made. 尽管从理论上讲,您可以通过sync
参数将jQuery.ajax强制设为sync
模式,但我不建议这样做,因为它会在发出请求时锁定浏览器UI。
You need to move your redirection code into the $.ajax
success
function like so: 您需要将重定向代码移至$.ajax
success
函数中,如下所示:
$.ajax({
url: 'http://example.com',
// ... other options omitted for brevity
success: function(data) {
// This code block gets executed when the operation completes.
var shouldRedirect = data.rows[0].redirectFlag
if (shouldRedirect) {
// Your redirection code goes here.
window.location = "...";
}
}
});
If you using of jQuery 1.7 or greater, you can make use their Promises/A implementation via the defered object . 如果您使用的是jQuery 1.7或更高版本,则可以通过defered object来使用其Promises / A实现。 Defered object's allow you to execute one or more functions when an operation completes and makes the async code easier to read. 延迟对象使您可以在操作完成后执行一个或多个功能,并使异步代码更易于阅读。
$.ajax({ url: 'http://example.com' })
.done(function(data) {
// This code block gets executed when the operation completes.
});
Instead of passing a function closure to done
, you can also pass a reference to a member function, eg: 除了传递函数闭包到done
,还可以传递对成员函数的引用,例如:
$.ajax({ url: url }).done(onDataLoaded);
function onDataLoaded(data) {
// This function gets called when the ajax operation completes.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.