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

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
17
Help us understand the problem. What is going on with this article?
More than 3 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

17
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

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
17
Help us understand the problem. What is going on with this article?