JQuery шаблон построения сетки - PullRequest
3 голосов
/ 23 января 2012

У меня есть JSON, как показано ниже

[
{
    "UserName": "John Robertson",
    "OperatorUserId": 1177,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 22,
    "CategoryWiseCount": 13,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [6, 1, 2, 0, 0, 0, 13, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "user1",
    "OperatorUserId": 39,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 13,
    "CategoryWiseCount": 1,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [1, 0, 3, 1, 1, 0, 0, 6, 1],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "Margaret Graham",
    "OperatorUserId": 1169,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 2,
    "CategoryWiseCount": 2,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [2, 0, 0, 0, 0, 0, 0, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "Stuart White",
    "OperatorUserId": 961,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 1,
    "CategoryWiseCount": 1,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "Bob van Schie",
    "OperatorUserId": 1007,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 1,
    "CategoryWiseCount": 1,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "Caird Hay",
    "OperatorUserId": 1184,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 1,
    "CategoryWiseCount": 1,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "bsoni",
    "OperatorUserId": 2575,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 3,
    "CategoryWiseCount": 2,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [0, 0, 0, 0, 1, 0, 2, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}, {
    "UserName": "tsname",
    "OperatorUserId": 2576,
    "PartCategoryID": 0,
    "PartCategoryName": null,
    "UnitCount": 1,
    "CategoryWiseCount": 1,
    "TotalUsers": 0,
    "TotalCategories": 0,
    "MainArrayCount": null,
    "NewMainArrayCount": null,
    "ListCategorywiseCount": [0, 0, 0, 0, 0, 1, 0, 0, 0],
    "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
    "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
}]

Я хочу посмотреть выше данные в сетке, используя шаблон jquery.

John Robertson    User1    Margaret Graham ..... 
Base unit            6             1          ...
Hard Drive           1             0          ...
.....

1 Ответ

1 голос
/ 26 января 2012

Объяснение

Есть несколько вещей, которые необходимо прояснить, прежде чем мы начнем.

Первый:
Я предполагаю, что под «шаблоном» вы подразумеваете плагин, потому что JQuery.template все еще находится в бета-версии, и его пока не рекомендуется использовать. Кроме того, это на самом деле мало что даст.

Вы можете узнать, как создавать свои собственные плагины, , начиная здесь , однако я собираюсь дать вам полный пример того, как это делается (далее).

Обычно, когда вам нужен элемент, связанный с вашим плагином, он начинается с

(function($) {
    //Prototype
    $.fn.myPlugin = function(){
         //Logic
         $(this).append("Hello world!");
    }
})(JQuery);

$("#element").myPlugin();

В противном случае, как общая функция, доступ к которой осуществляется через $, это просто

(function($) {
    //Prototype
    $.myPlugin = function(){
         //Logic
         alert("Hello world!");
    }
})(JQuery);

$.myPlugin();

Второй:
При отправке JSON через AJAX вы хотите привязать объект к вашему JSON, а не массив. JSON означает нотацию объектов JavaScript, поэтому даже смотря на имя, он должен сказать, что он имеет отношение к объектам.
Другими словами, вам нужно отправить обратно объект с помощью фигурных скобок {}.

Итак, ваш JSON должен выглядеть примерно так

{
    data: ["Hello ", 
           "World", 
           "!", 
           {time: "HH:mm:ss", date: "yyyy-mm-dd"}
}

Вы можете узнать больше о том, что это такое Википедия .

Третье:
Для пояснения, чтобы запросить данные JSON для вызова AJAX, вы должны указать dataType как JSON. Это сделано так

$.ajax({
    url: "example_json_output.txt",
    dataType: "json",
    success: function(json){
        alert(JSON.stringify(json));
    }
});

Обратите внимание, что я использовал функцию JSON.stringify, которая сериализует (помещает все переменные в текст) переменную. Отлично подходит для отладки! :)

В качестве альтернативы вы можете использовать сокращенную версию, getJSON

$.getJSON("example_json_output.txt", function(json) {
    alert(JSON.stringify(json));
});

Решение

Прежде чем дать вам код, вот скриншот того, как должен выглядеть ваш результат. How the result should look like

Конечно, я не говорю, что вы должны делать именно так, как я, на самом деле, я призываю вас сделать это по-другому. Практика делает идеальным. Кроме того, это может быть не тот тип макета, который вы хотели.

Как и было обещано, вот весь код для создания приведенного выше снимка экрана. Я начну с файла JavaScript и вывода JSON, так как они наиболее актуальны. Обратите внимание, что все файлы находятся в одной папке.

Файл: JavaScript "example.js"

$(document).ready(function(){
    $("body").myPlugin();
});

(function($) {
    $.fn.myPlugin = function(){
        //Internal reference
        var _this = this;

        //Begin request
        $.ajax({
            url: "example_json_output.txt",
            dataType: "json",
            success: Construct
        });

        function Construct(json){
            //Check if anything was returned
            if(json.data == null) return;

            //Main components
            var nMainContainer = $("<div>"),
                nListTable = $("<table>");

            nMainContainer.addClass("cMain");
            nListTable.addClass("cTable");
            nListTable.attr({"cellspacing":"0px", "cellpadding":"5px"})

            //Categories
            var aYHeaders = json.data[0].ListCategories;

            //Users row (top row)
            var nUserRow = $("<tr>");

            nUserRow.addClass("users");
            nUserRow.append($("<th>"));

            for(j = 0; j < json.data.length; j++){
                var nUser = $("<th>"),
                    sClass = "even";

                if(j % 2 == 0) sClass = "odd";

                nUser.addClass(sClass);
                nUser.append(json.data[j].UserName);

                nUserRow.append(nUser);
            }

            //Add users row to main table
            nListTable.append(nUserRow);

            //Begin iteration
            for(i = 0; i < aYHeaders.length; i++){
                //Category
                var nRow = $("<tr>"),
                    nHead = $("<th>"+aYHeaders[i]+"</th>"),
                    sRowClass = "even";

                //Check row number
                if( i % 2 == 0 ) sRowClass = "odd";

                nRow.addClass(sRowClass);

                //New category
                nRow.append(nHead);

                for(j = 0; j < json.data.length; j++){
                    //Data row from JSON
                    var oCurrentData = json.data[j];
                    var sUser = oCurrentData.UserName,
                        aListData = oCurrentData.ListCategorywiseCount,
                        sColumnClass = "even";
                    var nTableData = $("<td>");

                    //Check column number
                    if( j % 2 == 0 ) sColumnClass = "odd";
                    nTableData.addClass(sColumnClass);
                    nTableData.append(aListData[i]);

                    //Add data to current category row
                    nRow.append(nTableData);
                }
                //Add category row to main table
                nListTable.append(nRow);
            }

            //Add main table to container
            nMainContainer.append(nListTable);
            //Add container to this element
            $(_this).append(nMainContainer);
        }
    }
})(jQuery);

Файл: текстовый документ "example_json_output.txt"

{"data": [
    {
        "UserName": "John Robertson",
        "OperatorUserId": 1177,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 22,
        "CategoryWiseCount": 13,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [6, 1, 2, 0, 0, 0, 13, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "user1",
        "OperatorUserId": 39,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 13,
        "CategoryWiseCount": 1,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [1, 0, 3, 1, 1, 0, 0, 6, 1],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "Margaret Graham",
        "OperatorUserId": 1169,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 2,
        "CategoryWiseCount": 2,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [2, 0, 0, 0, 0, 0, 0, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "Stuart White",
        "OperatorUserId": 961,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 1,
        "CategoryWiseCount": 1,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "Bob van Schie",
        "OperatorUserId": 1007,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 1,
        "CategoryWiseCount": 1,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "Caird Hay",
        "OperatorUserId": 1184,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 1,
        "CategoryWiseCount": 1,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [0, 1, 0, 0, 0, 0, 0, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "bsoni",
        "OperatorUserId": 2575,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 3,
        "CategoryWiseCount": 2,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [0, 0, 0, 0, 1, 0, 2, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }, {
        "UserName": "tsname",
        "OperatorUserId": 2576,
        "PartCategoryID": 0,
        "PartCategoryName": null,
        "UnitCount": 1,
        "CategoryWiseCount": 1,
        "TotalUsers": 0,
        "TotalCategories": 0,
        "MainArrayCount": null,
        "NewMainArrayCount": null,
        "ListCategorywiseCount": [0, 0, 0, 0, 0, 1, 0, 0, 0],
        "ListCategories": ["Base Unit", "Hard Drive", "Laptop", "Laptop AC Adapter", "Motherboard", "Optical Drive", "Processor (CPU)", "Server", "TFT"],
        "ListUsers": ["John Robertson", "user1", "Margaret Graham", "Stuart White", "Bob van Schie", "Caird Hay", "bsoni", "tsname"]
    }
]}

Файл: HTML "example.html"

<html>
    <head>
        <link rel='stylesheet' type='text/css' href='example.css'>
        <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
        <script type='text/javascript' src='example.js'></script>
    </head>
    <body>
    </body>
</html>

Файл: CSS "example.css"

.cMain{padding: 5px;}
.cTable{border: 1px solid black;}

.cTable tr:first-child th{
    border-bottom: 1px solid black;
    text-align: center;
}

.cTable tr th:first-child{
    border-right: 1px solid black;
    text-align: right;
}

.cTable tr.odd td{background-color: #cbcbcb;}
.cTable tr.odd th{background-color: #b3b3b3;}
.cTable tr:first-child th.even{background-color: #accbe6;}
.cTable tr.even td.even{background-color: #cee1f2;}
.cTable tr.odd td.even{background-color: #a3c0d9;}
.cTable tr td{padding: 3px;}
.cTable tr:first-child th:first-child{background-color: #666;}
.cTable tr:first-child th:not(:first-child){width: 100px;}
...