Help us understand the problem. What is going on with this article?

PHPからJavaScriptへの値渡し

はじめに

PHPからJavaScriptへの値の渡し方を、phtmlで書いてまとめます。
なるべく同じような型として解釈されるように変換しています。

PHP(string) → JS(string)

test.phtml
<?php
    $foo = 'abcde';
?>

<script>
    let bar = '<?php echo $foo; ?>';
    console.log('typeof: ' + typeof bar);
    console.log('value: ' + bar);
</script>
console.log
typeof: string
value: abcde

PHP(integer) → JS(number)

test.phtml
<?php
    $foo = 12345;
?>

<script>
    let bar = <?php echo $foo; ?>;
    console.log('typeof: ' + typeof bar);
    console.log('value: ' + bar);
</script>
console.log
typeof: number
value: 12345

PHP(boolean) → JS(boolean)

test.phtml
<?php
    $foo = true;
?>

<script>
    let bar = Boolean(<?php echo $foo; ?>);
    console.log('typeof: ' + typeof bar);
    console.log('value: ' + bar);
</script>
console.log
typeof: boolean
value: true

PHP(array) → JS(object)

test.phtml
<?php
    $foo = [1, 2, 3, 4, 5];
    $foo = json_encode($foo);
?>

<script>
    let bar = JSON.parse('<?php echo $foo; ?>');
    console.log('typeof: ' + typeof bar);
    for (let i = 0; i < bar.length; i++) {
        console.log('value: ' + bar[i]);
    }
</script>
console.log
typeof: object
value: 1
value: 2
value: 3
value: 4
value: 5

PHP(array) → JS(object) [連想配列]

test.phtml
<?php
    $foo = ['key' => 'value', 'aaa' => 'bbb'];
    $foo = json_encode($foo);
?>

<script>
    let bar = JSON.parse('<?php echo $foo; ?>');
    console.log('typeof: ' + typeof bar);
    for (let key in bar) {
        console.log(key + ': ' + bar[key]);
    }
</script>
console.log
typeof: object
key: value
aaa: bbb

まとめ

Bool or Array を渡すときは、ひと手間必要です。

yuuto_odo
サーバーサイドエンジニア3年目です。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away