如何在Javascript中访问对象?

时间:2017-07-22 17:22:54

标签: javascript jquery

我是JS的新手。

所以我希望能够将货币,尤其是IDR兑换成美元。 我想使用fixer.io。所以这是我的代码:

function idr_to_usd(){
    var url = $.getJSON("http://api.fixer.io/latest?base=IDR&symbols=USD");
    var respon = url.responseJSON;
    var rates = respon.rates.USD;
    return rates;
}

它不起作用,在检查员中说: filename.js:46未捕获的TypeError:无法读取属性' rate'未定义的

但我直接在检查器控制台中尝试代码并且它可以工作。那我哪里做错了?感谢

2 个答案:

答案 0 :(得分:0)

这是你的解决方案:

    var usd_rate = 0;
    function idr_to_usd(){
        $.getJSON('http://api.fixer.io/latest?base=IDR&symbols=USD' , function(json_data){
            var rates = json_data.rates.USD;
            console.log(rates);    // check the console here.
            usd_rate = rates;
        });
    }

    idr_to_usd();

答案 1 :(得分:-3)

试试这个

function idr_to_usd(){
    var url = $.getJSON("http://api.fixer.io/latest?base=IDR&symbols=USD");
    var respon = JSON.parse(url.responseText);
    var rates = respon.rates.USD;
    return rates;
}

alert(idr_to_usd());

Url返回的响应文本是 JSON对象但是 stringify

你必须将你的json字符串转换为json对象,所以我的做法如下:

var respon = JSON.parse(url.responseText);

现在从回复中你可以得到费率。

如果要解除ajax结果,请运行以下代码段

  function idr_to_usd(){
       $.getJSON("https://api.fixer.io/latest?base=IDR&symbols=USD",function(data){
 		var USD=data.rates.USD;
        alert(USD);
})
};

idr_to_usd()
        
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>