开发者

how to pass variables from php page to javascript and display the data [duplicate]

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

how to pass the data which is stored in a variable from php to javascript and by using 开发者_C百科split function we are spliting the data and display it on the web age ....


At the risk of being shouted at for answering without context, I'm in a generous mood today :)

<?php 
   //do lots of stuff in my PHP page
   $var = 'somevalue';
?>
<html> 
  <head>
    <title>My page title</title>
    <script type='text/javascript'>
        var myJsVar = '<?php echo $var;?>'
    </script>
  </head>
  <body>
  </body>
</html>


Create whole javascript using PHP just like you're doing it with HTML


Assuming that you are writing the javascript in the .php file, you can write something like this

<script type="text/javascript">

var name = '<?php echo $name ; ?>';

</script>


The best way to do it, is by using JSON (a format for communication between server-side and client-side) http://www.javascriptkata.com/2007/05/08/how-to-use-json/


If you're not constructing the JavaScript in the php, and if it's only a small amount of data, you could also put it on the page in a hidden variable, and use JavaScript to access it that way.


As mentioned several times before you can just echo the content of the var within the javascript part of the webpage. But if you want to split the information to show in the webpage, you could this with PHP aswell.

Explode is the equivalent of Split in PHP. Perhaps you can explode it in PHP and show the values directly in the correct place.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜