27
25

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 5 years have passed since last update.

株式会社デジタルクエスト エンジニアAdvent Calendar 2019

Day 5

PHPからJavaScriptへの値渡し

Last updated at Posted at 2019-12-04

##はじめに
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 を渡すときは、ひと手間必要です。

27
25
1

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
27
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?