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

后端 未结 7 1703
无人及你
无人及你 2020-12-24 09:46

I have this following JSON data snippit:

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


        
相关标签:
7条回答
  • 2020-12-24 10:01
    $(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);
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-24 10:04

    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

    0 讨论(0)
  • 2020-12-24 10:05

    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.

    0 讨论(0)
  • 2020-12-24 10:18

    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>
    
    0 讨论(0)
  • 2020-12-24 10:22

    Try JsRender and JsViews or moustache/ember

    0 讨论(0)
  • 2020-12-24 10:25
    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.

    0 讨论(0)
提交回复
热议问题