我正在尝试检查是否定义了变量,如果是,则运行 ajax 请求...如果没有,我希望将用户重定向到设置变量的单独页面。
例如我想要这样的东西:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
因此,页面第一次运行时,它会检查变量是否已设置。如果未设置该变量,它将设置该变量,然后重新加载页面并再次运行检查。
问题是“accessKey”始终返回未定义,但代码运行起来就像变量已定义一样。为什么?
最佳答案
If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again
有一个问题:变量(或任何其他 js 代码)在页面重新加载之间不会保留。
如果您需要持久保存某些内容,则必须使用其中之一:
- 服务器端 session 或数据库(使用 ajax 将数据传递到服务器并将其保存在那里)
- 客户端存储(例如
localStorage
)。 - Cookie(可以在客户端或服务器端生成)
关于javascript - 检查未定义的 JavaScript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772894/