業界トップクラスの求人数を誇る転職エージェントPR

リクルートグループのコネクションを活かした非公開求人も充実、他にはない好条件の求人と出会える

16
19

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に値渡し

phpから外部のjavascriptに値を渡す方法を紹介します。
*JQueryも使います。
ほぼこちらhttps://qiita.com/cither/items/b98cc4e237dcc8f7e51f
の記事の一部を引っ張り出す形になっています、
さっそく中身に入っていきましょうー

index.php
//こいつを渡します
$param = "渡したい変数"

//JSON形式に変換する関数を定義
function json_safe_encode($data){
    return json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
}

//JQuery読み込み
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
//外部javascript呼び出し
//ここでid属性を記述して、スクリプトタグに変数を埋め込みます
<script id="script" type="text/javascript" src="./js/script.js"
 data-param='<?php echo json_safe_encode($param);?>'>
</script>

json_encode関数に毎回引数指定するのが面倒なので5行目で定義しています。

script.js
//JQuery使って属性を取得する、JSON.parseで扱える形に変換
var $script = $('#script');
var result = JSON.parse($script.attr('data-param');
//確認
console.log(result);

読んで字の如くですが、
参考になれば幸いです。

参照記事:
https://qiita.com/cither/items/b98cc4e237dcc8f7e51f

16
19
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
16
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?