首页 > 解决方案 > 将php数据传递给javascript

问题描述

尝试使用 javascript 从 mongodb 数据库中读取使用 php 7 检索的数据。如果我回显 $rows 变量,我如何捕获它以便我可以使用 javascript 进行处理。目前,当我尝试控制 $rows 数据时,它只控制一个空对象 {}。

php代码:

<?php

try {

    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $query = new MongoDB\Driver\Query([]);

    $rows = $mng->executeQuery("testdb.cars", $query);
    echo json_encode($rows);
    /*
    foreach ($rows as $row) {

        echo "$row->name : $row->price\n";
    }
     */


} catch (MongoDB\Driver\Exception\Exception $e) {

    $filename = basename(__FILE__);

    echo "The $filename script has experienced an error.\n";
    echo "It failed with the following exception:\n";

    echo "Exception:", $e->getMessage(), "\n";
    echo "In file:", $e->getFile(), "\n";
    echo "On line:", $e->getLine(), "\n";
}
?>

index.php 代码:

<body>
    <script>
    function reqListener () {
    console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest();
    oReq.onload = function() {

            console.log(this.responseText);
     };
    oReq.open("get", "get-data.php", true);

    oReq.send();
    </script>
</body>

标签: javascriptphp

解决方案


您可以将 php 响应解析为 json:

var myArr = JSON.parse(this.responseText);

在此处查看完整示例:https ://www.w3schools.com/js/js_json_http.asp


推荐阅读