Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  17] [ 4]  / answers: 1 / hits: 7567  / 11 Years ago, tue, january 21, 2014, 12:00:00

My HTML page primarily displays a list of pages retrieved from server.



I chose to implement this is in two parts




  1. Render the page without the list of pages with spinner.


  2. After the page is loaded I am making an AJAX call to retrieve the page list as JSON


  3. I am using jQuery as My javascript library




I get the JSON over AJAX which I need to convert into HTML and display in the page accordingly.



I have not done similar translation before so I would like to know what would be the optimal way to go ahead and transform JSON to html.



I did some research. I could see using some library or iterating each element and constructing the divs.



which would be the better one?



Sample of my JSON would be like



{
SomeID: 12345,
someName: somefile,
totalPageNum: 5,
pages: [ //Array of pages
{
pageFields: [ // Array of page fields
{
field: {
id: 1,
type: someType,
name: someFieldName,
value: Some Field Value
},
coordinates: {
x: 105,
y: 543
}
}
],
somePagenumber: 1,
somePageURLurl: /location/to/page1
}
]
}


Thanks for reading!!!


More From » jquery

 Answers
12

The term Optimal solution is biased.
What is a good solution for sure: Use JQuery to do it.



Example:



<!-- Include JQuery, only one time in the page header -->
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js></script>

<script>
$(document).ready(function(){
$.getJSON(/admin/json/endpoint,function(data) {
$.each(data.collection, function(i,e) {
var lmod = formatDate(new Date(e[lmodified]));
var row = <tr><td>+e[name]+</td><td>+lmod+</td>
$(#dpub tr:first).after(row);
});
});
</script>

<table id=dpub style=width:100%;>
<tr>
<th style=width:20%;>Name</th>
<th>Last modified</th>
</tr>
</table>


See: http://api.jquery.com/jquery.getjson/



console.log(data) can help you to understand the structure of the returned object in javascript. Open your browser javascript console to see the contents.



When things are getting complex and you don't only want to add simple rows to a table, consider to use a template engine like mustache.js


[#48479] Tuesday, January 21, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;