0

I have a JSON file named colors.js and looks like this:

{
    "colors": [
        {
          "color": "black",
          "category": "hue",
          "type": "primary",
          "code": {
            "rgba": [255,255,255,1],
            "hex": "#000"
          }
        },
        {
          "color": "white",
          "category": "value",
          "code": {
            "rgba": [0,0,0,1],
            "hex": "#FFF"
          }
        },
    ]
}

Here is how I have handled the html file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script type="primary" src="colors.json"></script>
    <script type="text/javascript">

      colorItems=['beige', 'red', 'blue'];

      function loadJSON() {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'colors.json', true);
        xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {              
              colorItems.push(JSON.parse(xobj.responseText)); // line 21
              console.log(xobj.responseText); // line 22

            }

          };
        }    

    function loadData(){
      for (i=0; i<4; i++){
          console.log(colorItems[i]);
          document.getElementById('myP1').innerHTML+=colorItems[i]+'<br>';
      }
    }
    </script>


    <title></title>
  </head>
  <body onload="loadData()">
    <p class="myP" id="myP1"></p>
    <p class="myP" id="myP2"></p>
    <p class="myP" id="myP3"></p>
    <p class="myP" id="myP4"></p>
    <p class="myP" id="myP5"></p>
  </body>
</html>

I need when the page loads, information from each object (in the JSON file) be pushed to colorItems array. Then, they array renders to the paragraphs (that have class myP) in the body. However, I face two problems:

  1. I am only able to get data to the paragraphs using getElementById, but not getElementsByClassName .
  2. I am not able to get the right data be pushed into colorItems array. Consequently, I am not able to get needed info on the html page.

This is how the output looks like (and how I need it to be): Visual description

2 Answers2

1

You might want to take a look at this answer: Can I access variables from another file?

Firstly, you are not correctly receiving your .json because you are not even calling loadJSON(). Functions can be defined and called. What you did was just defining two functions and then calling the second one through the "onload" parameter. You forgot to call loadJSON(). In case you don't know how to do this, you have to write loadJSON() right inside loadData.

Seconly, even if you call that function, it won't work because you are not working on a server. Thus, as the question in the link above says, you'll get this error:

XMLHttpRequest cannot load file:///[path-to-file]. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Regarding your first question, you should take a different approach. With a loop, you should create as many p elements as elements has the final colors array. Take a look at this guide: https://www.w3schools.com/js/js_htmldom_nodes.asp,

Nil
  • 61
  • 9
  • Thank you for the explanation. 1. I probably have to run a (dummy) server from my machine. Am I right? 2. I have got that fixed! – Alpha Bravo Charlie ... May 24 '18 at 19:24
  • 1
    If you are new to this, I do not recommend you to run your own server. Instead, search for some popular webserver that do that job for you! I recommend you DigitalOcean, which have a wide range of offers. – Nil May 24 '18 at 20:27
0

I think the way to push colors (object) to colorItems (array) could be this:

colorsjs.colors.map((o,i)=>{
     colorItems.push(o.color);
});

Then, in load data:

function loadData(){
      for (i=0; i<colorItems.length; i++){
          document.getElementById('myP'+(i+1)).innerHTML = colorItems[i]+'<br>'; 
      }
    } 

Full example here https://jsfiddle.net/or9o9upb/

If you want to iterate over the class element:

var el = document.getElementsByClassName("myP");

      for(let i = 0; i<el.length; i++){
      el[i].innerHTML = colorItems[i];
      }

Example here https://jsfiddle.net/8Lq2nd23/

If you have a js file with the json:

<script src="/path/to/colors.js"></script>

  <script>
//it's already available 
  console.log(colorsjs);
  </script>

But your js have to be something like this:

var colorsjs = {
    "colors": [//....code
Emeeus
  • 4,104
  • 2
  • 14
  • 32
  • Thank you. But I need the data be read from the JSON file, not available already (hard coded) in the html file. – Alpha Bravo Charlie ... May 24 '18 at 15:35
  • @MaYaNicolson it's the same idea, but I can't reproduce in jsfiddle or something – Emeeus May 24 '18 at 15:37
  • I understand. But a problem I already have (and mentioned in the main question) is that I am not able to get the data from the JSON file in the correct format. If you see my screenshot,'undefined' is rendered to the paragraphs. If you can post the solution to this issue as a comment or answer here, it will be great. – Alpha Bravo Charlie ... May 24 '18 at 16:08