質問

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!!!

役に立ちましたか?

解決

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

他のヒント

You could build the HTML as a string in JavaScript by iterating over each element and using string concatenation (as you mentioned).

You could also use a lightweight JavaScript template system for cleaner code. I recommend using mustache.js.

Either way, eventually you use something like jQuery's .html() to insert into the actual page.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top