首页 > 解决方案 > 在 $.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.

标签: javascriptjqueryconstantsuninitialized-constant

解决方案


推荐阅读