Search code examples
jqueryjsonajaxgetjson

How can I display the content from the .json file with jquery library?


i'm trying to get the data from my .json file (from the server) and just display it on the page. I'm not so good in the syntax of JS, i'm sorry.

I was trying to display only one parameter from the file but i don't see anything on the screen.

<html>
<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
</script>

<script>

$(function() {



$.getJSON("video.json", function(data)) {
   $.each(data.NewsSources, function(i, f) {
      var vid =  f.Name;
       $(vid).appendTo("#userdata");
 });

});

});
</script>
</head>

<body>


<div id= "userdata">
<h1>This is a name</h1>
</div>


</body>
</html>    

video.json

{
"NewsSources": [
{
  "ID": 2004,
  "Name": "365TV Brasil",
  "Description": "",
  "URL": "https://www.instagram.com/365scoresbra",
  "Lang": 31,
  "CountryID": 21,
  "LogoUrl": "",
  "ImgVer": 0
 }
 ]
 }

Solution

  • You have a small error, instead of $(vid).appendTo("#userdata") you should use $("#userdata").append(vid).

    data = {
        "NewsSources": [{
            "ID": 2004,
            "Name": "365TV Brasil",
            "Description": "",
            "URL": "https://www.instagram.com/365scoresbra",
            "Lang": 31,
            "CountryID": 21,
            "LogoUrl": "",
            "ImgVer": 0
        }]
    };
    $.each(data.NewsSources, function(i, f) {
        var vid = f.Name;
        $("#userdata").append(vid);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="userdata">
        <h1>This is a name</h1>
    </div>

    Also on JSFiddle.

    And why... well, doing $("365TV Brasil") is a jQuery selector which will select nothing on your page. On the other side, creating the text node in jQuery may be complicated. Therefor, better way is to use jQuery append method, which allows text as a parameter:

    DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.