jQuery cookie值作为AJAX响应变量

时间:2019-10-26 09:57:12

标签: jquery ajax variables

我在cookie中存储了货币代码。这个值看起来像(EUR,USD,GBP,THB ...) 我向免费的API(exchangeratesapi.io)发出AJAX请求,我想在其中将一定数量的THB(泰铢)转换为用户在Cookie中设置的任何货币。

    // Set currency cookie to GBP
    $.cookie("Currency", "GBP");

    // AJAX request to exchangeratesapi
    $.ajax({
        url: "https://api.exchangeratesapi.io/latest?base=THB",
        dataType: 'json'
    })
    .done(function(data) {
        // Set cookie value to var "tocur"
        var tocur = $.cookie("Currency");
        // Get exchange rate for GBP and store it in var "exchangerate" 
        var exchangerate = (data.rates.tocur);
        // Amount of THB to be exchanged to GBP
        var amount = 250;
        // Result for THB amount * exchangerate
        var sum = (amount * exchangerate);
        // Insert result into HTML element, roundet to 2 decimals, replace "." with ","
        $('#responsedata').html(amount + " THB = " + sum.toFixed(2).replace(".", ",") + " " + tocur);
    })
    .fail(function() {
        alert( "Could not fetch exchange rates" );
    });

这很好,只要我将变量“ exchangerate”手动设置为(data.rates.GBP)。尝试将其设置为(data.rates.tocur)时,结果就是NaN。

我想念什么吗?如何获取存储在var“ tocur”中的cookie值以在var exchangerate中工作?我需要以某种方式解析它吗?提前非常感谢您!

我也将其放在JS小提琴中:Here

0 个答案:

没有答案