passing variables from php to javascript [duplicate]
I am trying to create a site where someone can create an "item" and the database will store an id and php generates a url for that id. So next time when the person comes back with that url it will remember the person's settings (variables). Now the problem is that in my site javascript need to know these variables.
So what is the best solution for this? passing the variables in the superglobal "GET" or maybe cookies? Or is there a better way to pass these variables to javascript?
just use php to print some dynamic javascript
<script>
var myVar = "<?php echo json_encode($_COOKIE['somevalue']);?>";
</script>
There are multiple methods for providing the data to the client, such as:
- Echo the variables in your javascript,
var userid = <?php echo $userid; ?>
- JSON'fy your variables and supply them to your javascript via AJAX/jQuery:
$.getJSON(url, function(data){ var userid = data.userid; });
I typically utilize JSON as much as possible when trying to present server-side data to the client-side, as it helps to separate the different layers.
精彩评论