JS:在客户端为整个会话缓存字符串数组

JS: cache string array at client for entire session

我有一个下拉列表,显示一个国家/地区的所有城市 - 大约几千个字符串。

这是一个普通的 JS 数组,我想在整个会话期间将它存储在用户的缓存中,而不是让他的浏览器在每次请求时都下载它。

仅供参考,我使用 ASP.NET MVC,我认为这并不重要。 jQuery 也是我正在使用的库之一。

我更喜欢使用内置方式而不是将新库添加到我的代码中。

您可以使用 sessionStorage:

sessionStorage.setItem('cities', JSON.stringify([1, 2, 3]))
JSON.parse(sessionStorage.getItem('cities')) // [1, 2, 3]

data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.

有关 localStorage and sessionStorage

的更多信息