简体   繁体   中英

JSON, converting to HTML to use with Isotope.js

UPDATE: I have changed this question around. I was unable to figure it out, even though I'm sure I got two great answers. I have tried to simplify this question so I can figure it out in a more methodical manner. I hope this can help other newbs like myself...

I would like to use isotope.js to display selected data from a JSON (this question is related to the question I posted here):

Best way to create grid from JSON data which dynamically resizes based on number of entries

I've been reading about isotope today (I'm also a newbie to Javascript), and I'm sure this question will seem elementary to a lot of you. Anyways here goes...

From what I see, I need to have the html in this format to feed to isotope (this is taken from the basic example on isotope found here - https://github.com/DaweiCheng/isotope-tutorial/blob/master/basic.html ):

<div class="element other nonmetal   " data-symbol="H" data-category="other">
      <p class="number">1</p>
      <h3 class="symbol">H</h3>
      <h2 class="name">Hydrogen</h2>
      <p class="weight">1.00794</p>
    </div>

So, if I had a JSON like so (please assume multiple records that are similar):

[{"name":"Hydrogen","number":1,"symbol":"H","weight":1.00794},{"name":"Helium","number":2,"symbol":"He","weight":4.002602},{"name":"Lithium","number":3,"symbol":"Li","weight":6.941},{"name":"Beryllium","number":4,"symbol":"Be","weight":9.012182},{"name":"Boron","number":5,"symbol":"B","weight":10.811},...]

*Please note that any fields that are numbers in the JSON are integers, not strings.

I want to turn the JSON into this:

<div id="container">

<div class="element">
<p class="number">1</p>
<h3 class="symbol">H</h3>
<h2 class="name">Hydrogen</h2>
<p class="weight">1.00794</p>
</div>
<div class="element">
...
</div>

</div>

How would I convert the JSON into the required HTML?

To make things simple (for me), I want the div class for each record to always be element (so as I learn to change isotope, I can initially begin by using the css from their tutorials). The container div doesn't need to be repeated for each record, all the records will be displayed within the container (I guess that doesn't need saying)...

I have tried doing it using the answers below (which answer how I previously asked this question), however when doing so I either got nothing returned (and no errors in the console), or I got what appears like an empty table cell.

Any help is greatly appreciated. I'm very sorry to the two users who responded, I'm thankful for your help and I'll continue to play with your answers in the hope I figure it out.

Create a function whose role is to accept the result from your Ajax and it iterates over every object, grabs the requisite data from it and outputs a div with the needed information.

For example:

function renderUser(ajaxResponse) {

    // turn string response to JSON array
    var responseArray = JSON.parse(ajaxResponse);

    // make sure there is a response
    if (responseArray.length > 0) {

        // get container
        var container = document.getElementById("container");

        // iterate over each response
        for (var i = 0; i < responseArray.length; i += 1) {

            // create the elems needed
            var player = document.createElement("div");
            player.className = "players";
            player.data-Name = responseArray[i].name;

            var score = document.createElement("p");
            score.className = "score";
            score.innerHTML = responseArray[i].score;

            var name = document.createElement("h3");
            name.className = "name";
            name.innerHTML = responseArray[i].name;

            var city= document.createElement("p");
            city.className = "city";
            city.innerHTML = responseArray[i].city;

            // append them all to player wrapper
            player.appendChild(score);
            player.appendChild(name);
            player.appendChild(city);

            // append player to container
            container.appendChild(player);
        }
    } 
}

edit:

Took the liberty of making a fiddle to do exactly what you wanted here: http://jsfiddle.net/92FgL/

If you wanted to use more jQuery and less vanilla js you could do something like:

// document.ready shorhand
$(function() {
  var $container;

  // store destination element
  $container = $('#container');

  $.getJSON('myjson.json', function(data) {
    var items;

    // initialize array where we'll store html
    items = [];

    // loop through ajax response
    $.each(data, function() {
      var html;

      // build player html
      html = "<div class=\"players\" data-name=\"" + data.name + "\"> \
      <p class=\"score\">" + data.score + "</p> \
      <h3 class=\"name\">" + data.name + "</h3> \
      <p class=\"city\">" + data.city + "</p> \
      </div>"

      // add new html onto array
      items.push(html);
    });

    // squish all the html into a string
    items.join('');

    // set the html of the container to the html built above
    $container.html(items);
  });

  $container.isotope({
    itemSelector: '.players'
  });
});

You could use jQuery tmpl plugin. It's not developed anymore, but it works really well.

https://github.com/jquery/jquery-tmpl

Template defined in html

    <script id="myTmpl" type="x-jquery-tmpl">
        <div class="player" data-name="${name}">
            <p class="score">${score}</p>
            <h3 class="name">${name}</h3>
            <p class="city">${city}</p>
        </div>
    </script>

Data pushed to the tmpl with jquery. Note: you don't need to cycle through data with a $.each or for: you can push the whole array and the tmpl plugin will handle it, pushing the data to the template for each entry of the array.

    $.getJSON('myjson.json', function(data) {
         var items = $('#mytmpl').tmpl(data);
         //items is your html object containing a div for each element of data.
         //you can push it to the dom through jQuery 
         //or $container.isotope( 'insert', items );
    });

Hope it helps.

Please ask further if it's not clear.

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