如何在没有基础的情况下使用API​​?

时间:2017-11-28 13:43:51

标签: javascript api base

var currencies =['USD','AUD','BGN','BRL','CAD','CHF','CNY','CZK','DKK','GBP','HKD','HRK','HUF','IDR','ILS','INR','JPY','KRW','MXN','MYR','NOK','NZD','PHP','PLN','RON','RUB','SEK','SGD','THB','TRY','EUR'];

var cur = document.getElementById('CurrencyList');
var fragment = document.createDocumentFragment();
currencies.forEach(function(currency, index){
    var opt = document.createElement('option');
    opt.innerHTML = currency;
    opt.value = currency;
    fragment.appendChild(opt);

});

cur.appendChild(fragment);

var cur2 = document.getElementById('CurrencyList2');
var fragment = document.createDocumentFragment();
currencies.forEach(function(currency, index){
    var opt = document.createElement('option');
    opt.innerHTML = currency;
    opt.value = currency;
    fragment.appendChild(opt);

});

cur2.appendChild(fragment);
console.log(typeof(cur));
console.log(fragment);
console.log(cur2);    

function convertCurrency(){

    var from = document.getElementById("CurrencyList").value;
    var to = document.getElementById("CurrencyList2").value;
    console.log(to);
    console.log(from);
    var xmlhttp = new XMLHttpRequest();
    var url = 'http://api.fixer.io/latest?base='+ to+ '&symbols=' + from + ',' + to;

    xmlhttp.open('GET',url,true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var result = xmlhttp.responseText;
            console.log(result);
            var jsResult = JSON.parse(result);

            var fromAmount = jsResult.rates[to];
            var oneValue = from.value;

            var twoValue = (oneValue * to).toFixed(2);

            var amt = document.getElementById("fromAmount").value;
            document.getElementById("toAmount").value = (oneUnit * amt).toFixed(2);
            console.log(amt);
            console.log(oneUnit);
            console.log(jsResult);
        }
    }
}

如果我这样使用http://api.fixer.io/latest?symbols=' + from + ',' + to;我会获得默认的欧元货币,当我在我的代码中选择我获得NaN时。如果我将网址更改为http://api.fixer.io/latest?base=USD&symbols=' + from + ',' + to;,则美元为NaN。

0 个答案:

没有答案