Javascript 将html存储在json文件中并使用Jquery循环

Javascript 将html存储在json文件中并使用Jquery循环,javascript,php,jquery,ajax,gridster,Javascript,Php,Jquery,Ajax,Gridster,这是我的代码: $(document).ready(function () { $.getJSON("data.json", function(data) { if (data!=null) { response = JSON.parse(data) $.each(response, function(i,value) { var id_name;id_name="#";

这是我的代码:

$(document).ready(function () {

    $.getJSON("data.json", function(data) {
        if (data!=null) {  
            response = JSON.parse(data)
            $.each(response, function(i,value) {       
                var id_name;id_name="#";   
                id_name = id_name + value.id;       
                $(id_name).attr({"data-col":value.col, "data-row":value.row, "data-sizex":value.size_x, "data-sizey":value.size_y});
            });
        } else {   
            console.log('No data returned by the server. Continue with the default positions');   
        }
    });

    // widget_selector: "> ul"
    // Define which elements are the widgets. Can be a CSS Selector string or a jQuery collection of HTMLElements.

    // widget_margins: [3, 3]
    // Horizontal and vertical margins respectively for widgets.

    // widget_base_dimensions: [110, 110]
    // Base widget dimensions in pixels. The first index is the width, the second is the height.

    var grid_canvas = $(".gridster > ul").gridster({
        widget_margins: [3, 3],
        widget_base_dimensions: [150, 150],

        // serialize_params: function($w, wgd) { return { id: $($w).attr('id'),col: wgd.col, row: wgd.row,size_x: wgd.size_x,size_y: wgd.size_y }
        // A function to return serialized data for each each widget, used when calling the serialize method. Two arguments are passed: 
        // $w: the jQuery wrapped HTMLElement which is used to get the id, and wgd: the grid coords object with keys col, row, size_x and size_y.

        serialize_params: function($w, wgd) 
        {
            return {
                id: $($w).attr('id'),
                col: wgd.col, 
                row: wgd.row,
                size_x: wgd.size_x,
                size_y: wgd.size_y,
            };
        },

        // draggable.stop: function(event, ui){} -- A callback for when dragging stops.
        // You can also implement other draggable options based on your requirements
        // draggable.start: function(event, ui){} -- A callback for when dragging starts.
        // draggable.drag: function(event, ui){} -- A callback for when the mouse is moved during the dragging. 

        draggable: {
            stop: function(event, ui) {
                // .serialize( )
                // Creates an array of objects representing the current position of all widgets in the grid.
                // Returns an Array of Objects (ready to be encoded as a JSON string) with the data specified by the serialize_params option
                // JSON.stringify() converts a primitive value, object or array to a JSON-formatted string that can later be parsed with JSON.parse().

                var positions = JSON.stringify(this.serialize());

                // With HTML5, web pages can store data locally within the user's browser.
                // Earlier, this was done with cookies. However, Web Storage is more secure and faster. 
                // The data is not included with every server request, but used ONLY when asked for. 
                // It is also possible to store large amounts of data, without affecting the website's performance.
                // The data is stored in key/value pairs, and a web page can only access data stored by itself.

                localStorage.setItem('positions', positions);

                $.post(
                    "process.php",
                    {"positions": positions},
                    function(data) {
                        // this is where you can check if your data is sent to the server or not.
                        // A status of 200 implies success

                        console.log(data);
                        if (data==200)
                            console.log("Data successfully sent to the server");
                        else
                            console.log("Failed")
                    }
                );

            }
        }   
    }).data('gridster');

    $('.1x-add').on('click', function() {
        grid_canvas.add_widget('<li class="new">...</li>', 1, 1);
    });
    $('.2x-add').on('click', function() {
        grid_canvas.add_widget('<li class="new">...</li>', 2, 1);console.log($(".gridster > ul").html())
    });

    //Predefined colorscheme, right now static but should be imported from the users choice. Loops through all boxes and randoms a color out of the array.
    $('ul li').each(function () {
        var back = ["#475f7b;","#75879c","#a3afbd"];
        var rand = back[Math.floor(Math.random() * back.length)];
        $(this).css('background',rand);
    });
})
然而。。这只是硬编码元素的位置,我有一个新功能:

$('.1x-add').on('click', function() {
    grid_canvas.add_widget('<li class="new">...</li>', 1, 1);
});
这将正确地添加一个新的小部件,但我希望能够将完整的元素保存到json文件中,包括位置。比如:

[
    {<li id="1" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="2" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="3" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>}
] 
然后从json文件中循环它们

谁能帮我上路吗


或者将json保持在原来的位置,然后将元素存储在另一个json文件中

,因为您已经在使用jQuery,所以我想说您需要两种方法:var el=$'…'和el.prop'outerHTML'。前者从字符串创建DOM元素,后者在字符串中序列化DOM元素。@Codehiker类似这样的东西@是的!但是,当添加我的ajax调用时,它会在我的json文件中以wierd格式打印它:[\@Codehiker你能更新你的代码以便我能更好地查看/理解吗?
[
    {<li id="1" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="2" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="3" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>}
]