LANGUAGE/JAVASCRIPT

[JAVASCRIPT] php 변수를 javascript

보겸삼촌 2020. 3. 3. 23:08

PHP 변수를 javascript에서 사용하는 방법은 크게 두 가지가 있음

 

1. echo()

<?php
    $var_php = "from php variable to javascript variable";
?>

<script>
    var var_js = "<? echo $var_php ?>";
</script>

 

2. hidden()

<body>
    <?php
        $var_php = '';
        $var_php = 'test';
    ?>
    <form action="#">
        <input type="hidden" class="class" name="name_s" id="id_s" value="<?php echo $var_php?>">
    </form>
</body>
</html>

<script>
    var var_js1 = $("#id_s").val();
    var var_js2 = $(".class").val();
    var var_js3 = $('input[name=name_s]').val();

    console.log(var_js1);
    console.log(var_js2);
    console.log(var_js3);
</script>