简体   繁体   中英

JSON data to HTML using AJAX

I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.

`enter code here`
<html lang="en">
    <head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
    <p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
    var ourData = JSON.parse(ourRequest.responseText);
    renderHTML(ourData);
    function renderHTML(data) {
        var output = "";
        for (var key in data)
        {
            output += "<p>" + key + output + "</p>"
        }
}
};
</script>
</body>

The main issue is how your calling the api " http://api.fixer.io/latest ".rates You call rest endpoints by there address params or with query params.

Please see example below calling your specified endpoint. That should get you started

var myData = 'https://api.fixer.io/latest'

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
            let res = JSON.parse(xhttp.responseText)
            Object.keys(res.rates).forEach((e)=>{
                console.log(`${e}: ${res.rates[e]}`)
                //Add your stuff here
            })
    }
};

xhttp.open("GET", myData, true);
xhttp.send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM