如果串联,则AJAX中的JSON结果未定义

时间:2018-08-23 23:17:59

标签: javascript ajax

使用Ajax.get,我收到一个JSON对象,并且能够访问需要的属性

console.log(data.quotes.USDEUR)

但是,由于最后一个属性是通过用户用户输入更改的,因此我声明了一个变量来代替它,并且该变量显示为未定义:

var destinationCurrency = "USDEUR"  //It can change into "USDAUD, USDGBP, etc"
console.log(data.quotes.destinationCurrency)  // produces undefined

在网上寻找了一段时间。还尝试过字符串连接,然后尝试JSON.parse,但没有运气,有人可以帮忙吗? 下面是ajax调用和console.log。

  function convert() {
        $.get("http://apilayer.net/api/live?access_key=" + key + "&from=" + 
sourceCurrency + "&to=" + destinationCurrency)
            .done(function (data) {
                console.log(data)  //returns JSON
                console.log(data.quotes.USDEUR + "  This works!") //this works
                console.log("typeof - " + typeof(data.quotes.USDEUR))
                var destinationCurrency = "USDEUR"

                console.log(data.quotes.destinationCurrency + "  This doesn't work")
                console.log("typeof = " +typeof(data.quotes.destinationCurrency))
            })
            .fail(function (e) {
                alert(e)
            })
    }

从控制台日志中

{success: true, terms: "https://currencylayer.com/terms", privacy: 
"https://currencylayer.com/privacy", timestamp: 1535062191, source: 
"USD", …}privacy: "https://currencylayer.com/privacy"quotes: {USDAED: 
3.6732, USDAFN: 72.655033, USDALL: 108.999898, USDAMD: 483.674987, USDANG: 
1.84685, …}source: "USD"success: trueterms: 
"https://currencylayer.com/terms"timestamp: 1535062191__proto__: Object
currencyConverter.js:19 0.86644  This works!
currencyConverter.js:20 typeof - number
currencyConverter.js:23 undefined  This doesn't work
currencyConverter.js:24 typeof = undefined

0 个答案:

没有答案