42
43

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.

PHPからJavaScriptに配列を渡す

Last updated at Posted at 2017-10-14

JavaScriptを使いこなせるようになりたい途上。

さて、表題の件、結論はJSON形式で受け渡しをすればOK。

.php
$php_json = json_encode($php_array);
.js
var js_array = JSON.parse('<?php echo $php_json; ?>');

※参考サイト消えました…

【2018/10/01追記】

JSON.parseをかませるとむしろXSSを許してしまうので、使わない方がよさげです。
(参考)
PHPからJavascriptに値を渡すときの注意点(ダブルクオートとシングルクオート)

改.js
let js_array = <?php echo $php_json; ?>;

PHP5.4以降で使えるjson_encodeマルチバイト文字エスケープしないオプションがありますが、5.3以前なら(?)特に指定しなくても問題ない模様。

42
43
2

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
42
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?