2

I am trying to display data randomly in my file 'question.json' on HTML but somehow there's nothing happened. I'm starting to learn JavaScript and still don't know how to fix. Here's my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Answer Something</title>
    <script>
        $.getJSON('question.json', function(data){
            console.log(data)
            let questionList = data[Math.floor(Math.random()* data.length)];
            let display = document.getElementById('question');
            display.innerHTML = questionList;
        });
    </script>
</head>
<body>
    <nav>
        <a href="/ask">Quick Ask</a>
        <a href="/answers">Quick Answers</a>  
    </nav>
    <h1 id="question"></h1>
    <div>
        <button>Sai/Không/Trái</button>
        <button>Đúng/Có/Phải</button>
    </div><br>

    <div>
        <button>Kết quả vote</button>
        <button>Câu hỏi khác</button>
    </div>
</body>
</html>
zuc0n
  • 21
  • 2
  • 3
    Can you provide an example of `question.json` ? What's your `console.log(data)` display ? – Arthur Mar 11 '19 at 16:38
  • 1
    are you getting data from your json file? you can see this in browser network console – Artem Ilchenko Mar 11 '19 at 16:40
  • 3
    Correct me if I'm wrong but are you using jQuery `getJSON`? If so I don't see any reference to jQuery on your code. – DPac Mar 11 '19 at 16:42
  • 1
    The DOM might not be fully loaded when you try to access `document.getElementById('question')`. It's always good practice to trigger DOM manipulations inside a `window.onload`. – Nino Filiu Mar 11 '19 at 16:43
  • Your code is missing jQuery import. Try to add before the script tag: `````` – Salvatore Cozzubo Mar 11 '19 at 16:49
  • Does this answer your question? [JQuery - $ is not defined](https://stackoverflow.com/questions/2194992/jquery-is-not-defined) – Heretic Monkey Jun 15 '20 at 13:37

0 Answers0