简体   繁体   中英

How do I dynamically populate html elements with JSON Data with Javascript not jQuery?

I have this following JSON data snippit:

{"items": [
 {
   "title": "sample 1",
   "author": "author 1"
 },
 {
  "title": "sample 2",
  "author": "author 2"
 }
]}

How do I populate the following html elements with this data:

<div class="news-story">
 <h5>sample 1</h5>
 <p>By: author 1</p>
 <h5>sample 2</h5>
 <p>By: author 2</p>
</div>

I want accomplish this with Javascript not jQuery.

Loop through them and use the DOM functions:

var news = document.getElementsByClassName("news-story")[0];
var items = json.items;
for(var i = 0; i < items.length; i++) {
    var h5 = document.createElement("h5");
    h5.innerHTML = items[i].title;
    news.appendChild(h5);
    var p = document.createElement("p");
    p.innerHTML = items[i].author;
    news.appendChild(p);

}

http://jsfiddle.net/AWRAW/

getElementsByClassName will not work in versions of IE prior to 9. If you need to support those though, you're really better off using jQuery.

var div = document.getElementsByClassName('news-story')[0],
    h5 = div.getElementsByTagName('h5'),
    p = div.getElementsByTagName('p'),
    data = JSON.parse( my_JSON_data );

data.items.forEach(function(v,i) {
    h5[i].innerHTML = v.title;
    p[i].innerHTML = "By: " + v.author;
});

JSFIDDLE DEMO


If you need to support older browsers, you can use a typical for statement instead of the forEach method.

for( var i = 0; i < data.items.length; ++i ) {
    var v = data.items[i];
    h5[i].innerHTML = v.title;
    p[i].innerHTML = "By: " + v.author;
}

And I'd suggest using an ID instead of a class for the news-story element, so you can use getElementById instead (unless of course you have several of them) .

If that's impossible, you may want to use a compatibility function from MDN for getElementsByClassName .


If you needed to create the inner elements, then here's one way:

var div = document.getElementsByClassName('news-story')[0],
    data = JSON.parse( my_JSON_data ),
    html;

html = data.items.map(function(v,i) {
    return '<h5>' + v.title + '</h5>' +
           '<p>By: ' + v.author + '</p>';
}).join('');

div.innerHTML = html;

JSFIDDLE DEMO


@Xeon06 shows how in his answer using createElement() , which is arguably a better approach.

Here's how I'd do it:

var div = document.getElementsByClassName('news-story')[0],
    frag = document.createDocumentFragment(),
    data = JSON.parse( my_JSON_data );

data.items.forEach(function(v,i) {
    frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
    frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
});
div.appendChild( frag );

JSFIDDLE DEMO

And of course you can modify it to use a for statement instead:

var div = document.getElementsByClassName('news-story')[0],
    frag = document.createDocumentFragment(),
    data = JSON.parse( my_JSON_data );

for( var i = 0; i < data.items.length; ++i ) {
    var v = data.items[i];
    frag.appendChild( document.createElement('h5') ).innerHTML = v.title;
    frag.appendChild( document.createElement('p') ).innerHTML = "By: " + v.author;
}
div.appendChild( frag );

The benefit of using a documentFragment is that you can do a single append to the DOM via the fragment instead of multiple appends. This gives better performance, especially if you have a large set of data.

Better late than never... I recently made a lib to do just this!

FragBuilder is the library.. usage is pretty simple: for the example you have posted you would need to change around the JSON a bit to make it a bit more semantic...

var frag = [{"items": [
 {
   "title": "sample 1",
   "author": "author 1"
 },
 {
  "title": "sample 2",
  "author": "author 2"
 }
]}];

would become

var frag = [ { "childNodes" : [ { "childNodes" : [ { "textContent" : "sample 1" } ],
          "tagName" : "H5"
        },
        { "childNodes" : [ { "textContent" : "By: author 1" } ],
          "tagName" : "P"
        },
        { "childNodes" : [ { "textContent" : "sample 2" } ],
          "tagName" : "H5"
        },
        { "childNodes" : [ { "textContent" : "By: author 2" } ],
          "tagName" : "P"
        }
      ],
    "className" : "news-story",
    "tagName" : "DIV"
  } ];

then you would generate a DocumentFragment by calling FragBuilder(frag)

There is also a reverse function if you find it easier to template using HTML then convert to JSON https://gist.github.com/2313580 (note, whitespace between tags is not handled and will cause failures)

I've found that the most reliable way to create DOM elements is using the element.innerHTML property. Basically you'd have a DIV or SPAN at the place at the place on the page where you want to render the new HTML. Then you'd grab that span in javascripting using document.getElementById("DIV-ID") and then set the innerHTML property of the DIV to the new HTML that you would generate from the JSON object. There are a bunch of other JavaScript functions to create elements, but I've found that they're not always reliable and don't always have the best cross-browser support.

http://www.w3schools.com/jsref/prop_html_innerhtml.asp

Sample with no jQuery:

<html>
    <head>
        <title>test</title>
    </head>
    <body>
       <div class="news-story">
            <h5>sample 1</h5>
            <p>By: author 1</p>
            <h5>sample 2</h5>
            <p>By: author 2</p>
        </div> 
        <script type="text/javascript">
            var json = {
                "items": [
                    {
                    "title": "sample x",
                    "author": "author x"
                    },
                    {
                    "title": "sample y",
                    "author": "author y"
                    }
                ]
            };

            var bindDataToHTML = function(data, element) {
                 var h5 = null;
                 var p = null;
                 h5 = element.getElementsByTagName("h5");
                 p  = element.getElementsByTagName("p");
                 h5[0].innerText = data.items[0].title;
                 h5[1].innerText = data.items[1].title;
                 p[0].innerText = data.items[0].author;
                 p[1].innerText = data.items[1].author;
            };

            document.getElementsByClassName = function(cl) {
                var retnode = [];
                var myclass = new RegExp('\\b'+cl+'\\b');
                var elem = this.getElementsByTagName('*');
                for (var i = 0; i < elem.length; i++) {
                    var classes = elem[i].className;
                    if (myclass.test(classes)) { retnode.push(elem[i]); }
                }
                return retnode;
            };

            // For sample purpose, let's imagine this method is a callback
            // for a request that provides you with your json data
            var doRequest = function() {
                var data = json;
                var element = null;

                var x = document.getElementsByClassName("news-story");

                if((null != x) && (0 < x.length)) {
                    element = x[0];
                }
                bindDataToHTML(data, element);
            };

            (function() {
                doRequest();
            })();

        </script>
    </body>
</html>

尝试JsRender和JsViews或小胡子/余烬

$(document).ready(function () {
    loadfunctionAjax();
});
var loadfunctionAjax = function () {
    $.ajax({
        type: 'GET',
        url: '/Site/SocialLink',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var HTML = '';
            for (var i = 0; i < data.length; i++) {
                item = data[i];
                HTML += '<li><a class="" target="_blank" href="' + item.FALink + '"><i class="fa ' + item.FAIcon + '"></i>' + item.Name + '</a ></li > ';
            }
            $('#footerSocialNav').append(HTML);
        }
    });
}

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