javascript - 将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>
解决方案
您可以将 php 响应解析为 json:
var myArr = JSON.parse(this.responseText);
推荐阅读
- postgresql - 如何将项目添加到 postgress 中的本地函数数组?
- python - 如何每天在特定时间运行一个功能,然后在特定小时后停止?
- html - 同一行中的水平和垂直照片
- oracle - Power BI Oracle on Prem 网关问题 - 找不到请求的 .Net Framework 数据提供程序
- c# - 如何在 ASP.NET Core for JWT 中添加角色策略?
- css - Flex-box:未按预期对齐项目
- swift - 在不支持并发的函数中等待 Swift 5.5 中两个任务完成的正确方法是什么?
- vb.net - VB.net:Application.StartupPath 的问题
- reactjs - 放置在公用文件夹中时,图标在 IE 11 React 中不可见
- django - 如何修复 React-Django APP 的 Heroku 部署中的 Collectstatic 错误