简体   繁体   中英

How to retrieve string value from a json using javascript?

My site stores strings in a json file and uses javascript to retrive value to HTML. Here's simplified version of the function.

HTML:

<html>
<head>
    <script src="script.js"></script>
</head>

<body>
  This is a demonstration. The author is:
    <div>
      <div class="author"></div>
    </div>
</body>
</html>

Javascript:

request = new XMLHttpRequest();
request.open('GET', 'data.json', true);

request.onload = function () {
   obj = JSON.parse(request.responseText);
   obj.forEach(function (d) {
        var el = document.createElement('p');
        el.textContent = d.author;
        document.getElementsByClassName('author')[0].appendChild(el);
    });
};

request.send();

Json:

{
  "author": "John Doe"
}

Implementation: http://embed.plnkr.co/Ixrz9R2KVLXpOqa7mwyU

The code doesn't return author name in the HTML. Is there anyway to do this without using jQuery if possible.

The reason

You have to load scripts like this:

<script src="script.js"></script>

The solution

Remove

<link href="script.js">

, and put

<script src="script.js"></script>

onto right before the </body> .

I recommend you put your script onto right before the </body> in order to let it be executed after the DOM elements are loaded.


The code

data.json

[
    {"author": "K."},
    {"author": "Hello world"},
    {"author": "John Doe"}
]

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="author" content="K.">

    <title>Demo</title>
  </head>

  <body>
    <p>This is a demonstration. The author is:</p>
    <div class="author"></div>

    <script src="script.js"></script>
  </body>
</html>

script.js

const request = new XMLHttpRequest; // `()` isn't needed.
request.open("GET", "data.json", true);
request.addEventListener("load", _ => { // Arrow function
    const parsed = JSON.parse(request.responseText);
    parsed.forEach(({author}) => { // Destructuring, Arrow function, ...
        const authorElement = document.createElement("P");
        authorElement.textContent = author;
        document.querySelector(".author").appendChild(authorElement);
    });
});
request.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