How to store data on a page and retrieve it through jQuery?

I have an array of data that I will echo on the page using PHP, and I want JQuery to be able to parse it. However, I do not want the data to be visible to the user. I have for example:

<div id="data-1">
    <span id="width">5</span>
    <span id="height">10</span>
    <span id="depth">15</span>
</div>
<div id="data-2">
    <span id="width">10</span>
    <span id="height">20</span>
    <span id="depth">30</span>
</div>

I am wondering if I should store data in passes this way and then in jQuery, hiding them when loading and playing with data, getting range values ​​later:

$(document).ready( function() {
    $("#width, #height, #depth").hide();
    $("#data-*").click(function() {
        var width = $("#width", $(this)).text();
        var height = $("#height", $(this)).text();
        var depth = $("#depth", $(this)).text();
    });
});

Is this the most efficient way to store data on a page? Should I use hidden inputs instead, or are there other ways to do this?

+3
source share
5 answers

PHP, json_encode(), javascript, jQuery. AJAX.

PHP:

$my_data = array(
   'data1' => array(
      'width' => 16,
      'height' => 20
    ),
   'data2' => array(
      'width' => 16,
      'height' => 20
    )
);

# echo at bottom of page
echo '<script type="text/javascript">';
echo 'window.my_data = '.json_encode($my_data);
echo '</script>';

JQuery

var height = window.my_data.data1.height
+7

, ajax, , , ajax. , , . Ajax - javascript, .

, php script php?

$(document).ready( function () {
   $("#data-*").click(function() {
      var width = <?=$width_var_in_php?>;
      var height = <?=$height_var_in_php?>;
   });
});

php , . , javascript , .

0

span, jQuery , - .

, :

<div id="data-1" class="{width: 5, height: 10, depth: 15}"></div>
0

HTML?

JSON?

var data1 = {
                width: 5,
                height:10,
                depth:15
             }
...
0

HTML-, JQuery, jSonComments - : http://plugins.jquery.com/project/jSonComments

JSON HTML- HTML-.

<div id="getMyData">
<!-- Metadata
        {
        "foo":"bar"
        }
-->
</div>

:

$('div#getMyData').jSonComments().foo

duckyflip, HTML, json_encode() PHP.

0

Source: https://habr.com/ru/post/1708913/


All Articles