Javascript stops working after PHP tag

2019-08-20 05:47发布

I have set session variable 'activeAcademicyearStartsOn' at the time of login.

If we var_dump() the session variable in view.php, the output is like

  object(stdClass)#11 (1) { ["$date"]=> object(stdClass)#12 (1) { ["$numberLong"]=> string(13) "1546297200000" } }

Now in view.php file, I am trying to get session variable in a javascript code inside javascript tag like

  $("#session_start_date").val(getDateString('<?php echo $_SESSION['activeAcademicyearStartsOn'] ?>'));

All the Javascript stops working.

     <script type="..">
        ...
        ...   
        $(document).ready(function(){  
        ...   
             $("#session_start_date").val(getDateString('<?php echo $_SESSION['activeAcademicyearStartsOn'] ?>'));
        ...
        });

        function getDateString(str)
        {
            if (str == '')
                return;

            var dateObj = new Date(str.$date.$numberLong - 1000);
            var month = dateObj.getMonth() + 1; //months from 1-12
            var day = dateObj.getDate();
            var year = dateObj.getFullYear();

            return (month + "/" + day + "/" + year);
        }          
        </script>

In order to test, if I put another session variable it works fine like

    $("#session_start_date").val('<?php echo $_SESSION['uid'] ?>');

Any help appreciated.

2条回答
戒情不戒烟
2楼-- · 2019-08-20 05:54

Seems to me your echoing an object in php, into a quoted string in javascript, and your using it as a object in your function.

If you take your php object, and convert it into a javascript object it should work better i think.

$("#session_start_date").val(getDateString(<?php echo json_encode($_SESSION['activeAcademicyearStartsOn']); ?>));
查看更多
Melony?
3楼-- · 2019-08-20 06:06

You will need to do 2 things

  1. Pass a json_encoded string to the javascript invocation, as mentioned by @Noino .

$("#session_start_date").val(getDateString(<?php echo json_encode($_SESSION['activeAcademicyearStartsOn']); ?>));

(This entire peice of code is 1 single line.)

  1. Parse this JSON string to make it a javascript object before using the values.

str = JSON.parse(str);

inside the getDateString() function.

查看更多
登录 后发表回答