我从货币层获得免费会员资格。我想转换货币但不允许免费会员资格。相反,他们为我提供了LIVE API
,我可以获得当前的汇率。因此,我决定通过使用jQuery代码进行一些tic tac来使用这个实时API进行货币转换。我在某种程度上修改了代码,我想我差点成功(也许我错了)。我对jQuery的工作知识有限,所以我在最后一点陷入困境。以下是解释该问题的代码。
从他们那里收到的API
// set endpoint and your access key
endpoint = 'live'
access_key = 'YOUR_ACCESS_KEY'; // can't reveal API key
// get the most recent exchange rates via the "live" endpoint:
$.ajax({
url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,
dataType: 'jsonp',
success: function(json) {
// exchange rata data is stored in json.quotes
alert(json.quotes.USDGBP);
// source currency is stored in json.source
alert(json.source);
// timestamp can be accessed in json.timestamp
alert(json.timestamp);
}
});
我尝试了什么
// set endpoint and your access key
endpoint = 'live'
access_key = 'YOUR_ACCESS_KEY'; // can't reveal API key
var from = $('#from').val();
var to = $('#to').val();
var combine = from+to;
// get the most recent exchange rates via the "live" endpoint:
$.ajax({
url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,
dataType: 'jsonp',
success: function(json) {
// exchange rata data is stored in json.quotes
//var response = json.quotes.combine;
alert(json.quotes.combine); // HERE IN PLACE OF USDGBP I USED THE COMBINE VARIABLE
$('#convert').html('response');
}
});
上面使用的 combine
变量返回undefined。也许我没有正确编码,因为我有限的jquery知识。如果我可以解决这个问题,那么我将最有可能使用该代码。请帮帮我。
答案 0 :(得分:2)
要通过保存其名称的变量访问对象属性,您需要使用括号表示法。要设置input
的值,请使用val()
。试试这个:
success: function(json) {
var value = json.quotes[combine];
$('#convert').val(value);
}