开发者

passing variables from php to javascript [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? 开发者_JAVA技巧 (19 answers) Closed 8 years ago.

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:

  1. Echo the variables in your javascript, var userid = <?php echo $userid; ?>
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜