简体   繁体   English

传递一个PHP对象以在外部JS脚本中使用

[英]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() . 我正在从数据库中获取一些信息,然后使用json_encode()将其传递给一些JavaScript。 The line: var row_data = <?php echo $month_stats ?>; 该行: var row_data = <?php echo $month_stats ?>; is dumping the object into the JS. 将对象转储到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. 但是现在我想将我的JS抽象到一个外部文件中,所以突然间我不能仅仅将对象的内容echo显到JS中,因为PHP在那里不存在任何内容。

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. 因此,我需要以某种方式(通过AJAX?)将PHP对象$month_stats直接发送到JS,以便它可以独立于PHP使用信息,但是我不确定如何实现。 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. 将JS放入外部文件时,使其具有一个参数即可。

In your .js file: 在您的.js文件中:

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

In your .php file: 在您的.php文件中:

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

To log the stats, you can call in the php file. 要记录统计信息,您可以调用php文件。

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

More info on JS Functions 有关JS函数的更多信息

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. row_data现在是全局变量,因此您可以在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 您可以在.js文件中创建一些javascripn函数

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

in your php file you can do that: 在您的php文件中,您可以执行以下操作:

<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. 如果您在包含的Javascript文件中引用变量row_data ,则它应该起作用,因为您在全局范围中声明了该变量。 Here's one article for reference: http://snook.ca/archives/javascript/global_variable 这是一篇供参考的文章: http : //snook.ca/archives/javascript/global_variable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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