简体   繁体   中英

Get php object defined in class to javascript in separate file

I haven't done much web development, to preface. I have a methodExec.php file and a main.js file. 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. 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

<?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) . In this instance, it returns null, which I can understand, but I'm not sure how to make it wait or any alternatives. Thanks in advance!

It probably is null because the browser load main.js file to the memory before then the jsArray was initialized. It may cause jsArray empty because does not exist in time call.

The function what you want to call with jsArray variable you can wrap javascript function setTimeout() . Try set it up to 200-300ms It should be ok. It will be call your function after that everything was initialized.

It is similar principle as jQuery.ready() function at jQuery library. It say's

"Run the code only if the jQuery is in state ready."

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