How to Get JSON Data

Asked

Viewed 878 times

1

Guys I made a list in JSON with the name of lista_json.js and put it in the head HTML, but I’d like to take it from body, codes work on the console but I can’t print on the screen, which I’m doing wrong?

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script language="JavaScript" src="lista_json.js" ></script>
    </head>
    <body>
    <h1>lista</h1>
        <p id="teste"></p>
        <script language="JavaScript" src="lista_json.js" > 

            document.getElementById("teste").innerHTML = pag_1.produto;

        </script>

    </body>
</html>

The file lista_json.js:

var pag_1 = {"produto":"produto1", "valor":1}; 
var pag_2 = {"produto":"produto2", "valor":2}; 
var pag_3 = {"produto":"produto3", "valor":3}; 
var pag_4 = {"produto":"produto4", "valor":4}; 
var pag_5 = {"produto":"produto5", "valor":5}; 
var pag_6 = {"produto":"produto6", "valor":6}; 
var pag_7 = {"produto":"produto7", "valor":7}; 
var pag_8 = {"produto":"produto8", "valor":8};
  • Do you have any error on the console? nothing appears?

  • No and in the console I take the data, print in various ways. However it does not work in html.

  • "However it does not work in html", you can explain better?

3 answers

1

Use it out of the <script src="">

<script language="JavaScript" src="teste.js" ></script>
<script>
    document.getElementById("teste").innerHTML = pag_1.produto;
</script>

1

your error 'and in the tag format script

<script type="text/javascript"> 
    document.getElementById("teste").innerHTML = pag_1.produto;
</script>

in Html5 it is not necessary to use type="text/javascript" recommending to html4-

extra you can do all your json together:

var pag_1 = [{"produto":"produto1", "valor":1},{"produto":"produto2", "valor":2}];

and access from this form pag_1[1].produto

-1

Use Jquery’s getJSON function:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.getJSON("lista_json.js", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });
    });
});
</script>
</head>
<body>

<button>Get JSON data</button>

<div></div>

</body>
</html>

(Will not appear the nothing pq does not have the JSON, example taken from the site W3school)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.