What is the best practice for transferring a variable value in javascript from a server?

I am developing a pet project using jQuery. Now the application requires that some variable value be passed to the javascript client when the page loads. I wonder what is the best thing to do.

I can do this in two ways. First, make it a javascript variable on the page.

<script> <?php echo "var maxid = $maxid;"?> </script>

This means that the client will see

<script> var maxid = <somevar>; </script>

Secondly, assign it an attribute of a single element.

<div maxid="<php echo $maxid >" />

Which approach is better? Is there any other way to do this?

+3
source share
6 answers

html , , .

<script>
$(function() {
    var max_id = <?php echo $max_id;?>;
});
</script>
+7

... , :

var myAwesomeStuff = <?php echo json_encode($myArrayOfAwesomeInformation); ?>

, JSON.

+1

- :

, "" , "". , "".

- :

HTML, , , ajax.

, JavaScript, JavaScript HTML/ .

, .

0

javascript ( ). , -, .

0

, . DIV, DOM DOM node .

0
source

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


All Articles