Converting json data to an HTML table

前端 未结 4 919
心在旅途
心在旅途 2021-01-03 09:43

I have an array of data in php and I need to display this data in a HTML table. Here is what an example data set looks like.

Array(
  Array
  (
     [compar         


        
4条回答
  •  天涯浪人
    2021-01-03 10:13

    That depends. There are several factors to be taken into account:

    1. How much CPU and network bandwidth do you want to waste on the webserver? Generating and sending HTML eats more than just sending a compact JSON string.

    2. How much CPU and memory do you want to waste on the webbrowser? Generating a table in HTML DOM tree eats more than just inserting a ready-generated string as innerHTML.

    3. How reuseable do you want the webservice to be? Returning "static" HTML isn't useful for everyone. A more flexible format like XML or JSON is more useful (also for yourself in the future).

    As far, I'd suggest returning JSON and have JS/jQuery to populate it on the client side.


    Update: assuming that the JSON data will arrive in this format

    var json = {"features": [{
        "comparisonFeatureId": 1182,
        "comparisonFeatureType": "Category",
        "comparisonValues": [ "Not Available", "Standard", "Not Available", "Not Available" ],
        "featureDescription": "Rear Seat Heat Ducts"
    }, {
        "comparisonFeatureId": 1183,
        "comparisonFeatureType": "Category",
        "comparisonValues": [ "Not Available", "Standard", "Not Available", "Not Available" ],
        "featureDescription": "Some Description"
    }]};
    

    and that you have an empty table like this

    then you can use the following jQuery script to fill it the way you described in the question

    $.each(json.features, function(i, feature) {
        var row = $('').appendTo($('#table'));
        row.append($('').append($('').text(feature.featureDescription)));
        $.each(feature.comparisonValues, function(j, comparisonValue) {
            row.append($('').text(comparisonValue));
        });
    });
    

提交回复
热议问题