Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
43
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@tksnino

PHPからJavaScriptに配列を渡す

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以前なら(?)特に指定しなくても問題ない模様。

43
Help us understand the problem. What is going on with this article?
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
43
Help us understand the problem. What is going on with this article?