简体   繁体   English

将类中定义的php对象获取到单独文件中的javascript

[英]Get php object defined in class to javascript in separate file

I haven't done much web development, to preface. 作为序言,我没有做太多的Web开发工作。 I have a methodExec.php file and a main.js file. 我有一个methodExec.php文件和一个main.js文件。 In my PHP file, I'm creating a list containing rows from a database and I'm trying to use that list in my .js file. 在我的PHP文件中,我正在创建一个包含来自数据库的行的列表,并且试图在我的.js文件中使用该列表。 I can access it if I declare the array outside of the class, but I'm not sure how to reference it after collecting the rows in the database. 如果我在类外声明了数组,则可以访问它,但是我不确定在收集数据库中的行后如何引用它。

methodExec.php methodExec.php

<?php

require_once 'includes/constants.php';

$methodExecVar = new methodExec();

class methodExec {
    private $conn;
    public $timesList;

    function __construct(){
        $this->conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD, DB_TIMES) or 
                die('There was a problem with the database connection.');
    }

    function getTimes(){

        $timesList = [];
        $query = "SELECT *
                    FROM times";

        $result = $this->conn->query($query);

        while ($row = $result->fetch_assoc()) {
            $timesList[] = $row;
        }

        $this->conn->close();

        return $timesList;
    }
}
?>

<script type="text/javascript">var jsArray = <?php echo json_encode($methodExecVar->timesList); ?>;</script>
<script type="text/javascript" src="js/main.js"></script>

main.js only includes alert(jsArray) . main.js仅包含alert(jsArray) In this instance, it returns null, which I can understand, but I'm not sure how to make it wait or any alternatives. 在这种情况下,它返回null,我可以理解,但是我不确定如何使其等待或有其他选择。 Thanks in advance! 提前致谢!

It probably is null because the browser load main.js file to the memory before then the jsArray was initialized. 它可能为null因为在初始化jsArray之前,浏览器将main.js文件加载到内存中。 It may cause jsArray empty because does not exist in time call. 这可能导致jsArray为空,因为在时间调用中不存在。

The function what you want to call with jsArray variable you can wrap javascript function setTimeout() . 您想使用jsArray变量调用的函数可以包装javascript函数setTimeout() Try set it up to 200-300ms It should be ok. 尝试将其设置为200-300ms,应该没问题。 It will be call your function after that everything was initialized. 一切初始化之后,将调用您的函数。

It is similar principle as jQuery.ready() function at jQuery library. 它的原理与jQuery库中的jQuery.ready()函数相似。 It say's 它说

"Run the code only if the jQuery is in state ready." “仅当jQuery处于就绪状态时才运行代码。”

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

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