javascript - 在 $.ajax 之后为全局变量赋值并表现得像一个 const
问题描述
你好吗?我想知道,有一种方法可以在 js 中声明一个不可变变量(如 const 关键字),但在 ajax 请求或 fetch 之后只分配一次值?
我的问题很简单:当文档加载时,我需要从服务器检索 3 个 _id,并且我需要将它们存储在某个全局变量中。我需要这 3 个 _id 是不可变的,因为站点上的所有下一个 ajax 请求都依赖于这些,我不能让别人更改这些变量中的值。
const 关键字是完美的,但我没有使用它们的范围,或者我无法在 ajax 请求之前声明变量。
有解决方法吗?
const _id1 = null; // Correct, but this means nothing to me
const _id2; // Error: Missing initializer in const declaration
let _id_3 = null; // Formally correct, I can assign a new value to the variable
// but everybody can modify it from the console...
// What I need to do is
// 1) declare the variable
let magic_id;
// 2) do my ajax calls to my server
$.ajax({
url, data, type, ...,
success(payload){
// 3) Assign the value to my id
let aPay = JSON.parse(payload);
magic_id = aPay._id;
}
});
// 4) If someone tries to assign a new value i need to prevent it
magic_id = new_value; // Uncaught TypeError: Assignment to constant variable.
解决方案
推荐阅读
- javascript - 提交时更改表单操作属性
- c# - Xamarin 表单 - 未找到绑定属性
- python - 在完成循环之前执行 for 循环之后的代码
- hibernate - 事务类中的JPA不必要的用户类
- google-chrome - 不允许加载本地资源,Chrome 服务器
- html - 在CSS中放入一些内容后如何初始化div宽度并自动更改?
- javascript - 如何将函数中的逻辑动态注入脚本元素
- c - fscanf 将其变量添加到另一个预定义变量中?
- mysql - mysql select查询与两列的sum和group by
- r - 如何从与数据框中其他列的最大值对应的列中检索值