I've written two complementary functions in javascript to get exchange-rates (based on the code found here) but I can't understand why it can't be only in one function. This is the code who works :
var money;
function showRate() {
getRate('EUR','USD');
alert(money);
}
function getRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://rate-exchange.appspot.com/currency?from="+from+"&to="+to+"&format=json&callback=sendRate");
document.body.appendChild(script);
}
function sendRate(data) {
money = parseFloat(data.rate, 10);
}
The code is a modification of the source, I've understand the code but not the line document.body.appendChild(script);
.
But my question is : why I've to do two separates functions (getRate
and sendRate
)? I've tried many things but something like that doesn't work :
function showRate() {
alert(getAndSendRate('EUR','USD'));
}
function getAndSendRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://rate-exchange.appspot.com/currency?from="+from+"&to="+to+"&format=json");
return(parseFloat(document.body.appendChild(script).data.rate, 10));
}
Could someone explain me why the second part of code doesn't work and if it can be fixed ?
Thanks!