gpt4 book ai didi

javascript - Money.js + LocalStorage 费率

转载 作者:行者123 更新时间:2023-11-30 17:09:57 28 4
gpt4 key购买 nike

我正在使用 Intel XDK 制作一个转换工具,我的脚本检测设备是否有互联网连接,如果是,使用它通过 JSON 从 openexchangerates 获取最新汇率并将其存储在本地存储中:

$.getJSON('https://openexchangerates.org/api/latest.json?app_id=XXXXXXXXXXXXXXXXXXXXXXXXXX',function(data) {
var localData = JSON.stringify(data);
localStorage.setItem('convrates', localData);
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base
}
}
});

没关系!但是当尝试从本地存储中获取此信息时,没有任何反应......

var localData = JSON.parse(localStorage.getItem('convrates'));
$.getJSON(localData,function(data) {
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base
}
}
});

这是 JSON 数据示例:

{
"disclaimer": "Exchange rates are provided for informational purposes only, and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, NO guarantees are given whatsoever of accuracy, validity, availability, or fitness for any purpose - please use at your own risk. All usage is subject to your acceptance of the Terms and Conditions of Service, available at: https://openexchangerates.org/terms/",
"license": "Data sourced from various providers with public-facing APIs; copyright may apply; resale is prohibited; no warranties given of any kind. Bitcoin data provided by http://coindesk.com. All usage is subject to your acceptance of the License Agreement available at: https://openexchangerates.org/license/",
"timestamp": 1417507252,
"base": "USD",
"rates": {
"AED": 3.673268,
"AFN": 57.871426,
"ALL": 112.5408,
"AMD": 439.297503,
"ANG": 1.7891,
"AOA": 101.106125,
"ARS": 8.531535,
"AUD": 1.174523,
"AWG": 1.79,
"AZN": 0.783933,
"BAM": 1.570651,
"BBD": 2,
"BDT": 77.73667,
}
}

我真的不知道怎么做。

最佳答案

您可以像对待普通 JS 对象一样对待 localStorage,因此首先您不需要对 JS 对象进行字符串化和解析。而不是写作

var localData = JSON.stringify(data);
localStorage.setItem('convrates', localData);

你可以这样做

localStorage['convrates'] = data;

甚至

localStorage.convrates = data;

要检索数据,您可能仍想使用 getItem(),因为如果 convrates 不存在,这将返回 null 而不是抛出错误,因此再次检索数据,您只需这样做

data = localStorage.getItem('convrates');

这将留下 data null 或最近存储在那里的 convrates 对象。

localData 上调用 $.getJSON 没有任何意义,因为那是 JS 对象,而不是 URL。

关于javascript - Money.js + LocalStorage 费率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com