0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPの変数をJavaScriptで使いたい(PHP変数をJavaScriptへ渡す方法)

Last updated at Posted at 2021-07-06

PHPファイルでPHPの変数をJavaScriptで使う方法(JavaScriptへ渡す方法)をメモ的にまとめておきます。

#数値・文字列を渡すとき:そのままecho

sample.php
<?php
$num = 1;
$str = 'abc';
?>

<script type="text/javascript">
var num = <?php echo $num; ?>;
console.log(num); // 1
var str = '<?php echo $str; ?>';
console.log(str); // abc
</script>

#配列を渡すとき:json_encodeでJSON形式にして渡す

sample.php
<?php
$hoge = array('aaa', 'bbb');
?>

<script type="text/javascript">
var hoge = JSON.parse('<?php echo json_encode($hoge)?>');
console.log(hoge); // ["aaa", "bbb"]
</script>
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?