简体   繁体   中英

Pass a PHP object for use in an external JS script

I'm grabbing some information out of a database and passing it to some JavaScript using json_encode() . The line: var row_data = <?php echo $month_stats ?>; is dumping the object into the JS.

But now I want to abstract my JS into an external file, so suddenly I can't just echo the contents of the object into the JS since PHP won't have any presence there.

So I need to somehow (via AJAX?) send the PHP object $month_stats directly to the JS so that it can use the information independently of PHP, but I'm not sure how this is implemented. Any pointers?

<?php

include 'db.php';

$month_stats = generate_monthly_count_stats($conn);
?>

<!DOCTYPE html>
<html>
    <head>

    <script type="text/javascript">

    var row_data = <?php echo $month_stats ?>;
    console.log(row_data);

    </script>

    </head>

    <body>
    </body>
</html>

When you put the JS into an external file, make it a function with one parameter.

In your .js file:

function logRowData(var1)
{
    console.log(var1);
}

In your .php file:

<head>
<?php
    include(filename.js);
?>
</head>

To log the stats, you can call in the php file.

<script type="text/javascript">
    logRowData($month_stats)
</script>

More info on JS Functions

You can simply echo the variable and access it in an external file:

<script type="text/javascript">var row_data = <?php echo $month_stats ?>;</script>
<script type="text/javascript" src="external.js"></script>

row_data is now a global variable, so you can access it in the external.js. However it is better to add it to a namespace if you have lots of other variables..

You can create some javascripn function in .js file

myFunction(obj) {
    console.log(obj);
}

in your php file you can do that:

<script type="text/javascript">
myFunction(<?php echo $month_stats ?>);
</script>

If you reference the variable row_data in your included Javascript file, it should work, as you are declaring that in the global scope. Here's one article for reference: http://snook.ca/archives/javascript/global_variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM