javascript - Codeigniter:如何将数据库结果转换为 JSON
问题描述
我正在尝试使用我的数据库中的结果填充我的 Google Map API。我的计划是将查询结果传递给 Javascript,以便它可以在 Lat 和 Lng 输出上绘制标记。
///Model
public function getLatLng(){
$this->db->select('*');
$this->db->from('tbl_loc');
$query = $this->db->get();
return json_encode($query->result());
}
///Controller
public function populateMaps(){
$data['loc'] = $this->user_model->getLatLng();
$this->load->view('maps', $data);
}
///View
<div id="getAddress">
<?php foreach($loc as $lc){
echo $lc;
?>
</div>
///JS
var getAllData = JSON.parse(document.getElementById('getAddress').innerHTML);
showAllLoc(getAllData);
function showAllLoc(getAllData){
Array.prototype.forEach.call(getAllData, function()){
var marker = new google.maps.Marker({
position : new google.maps.LatLng(getAllData.Lat, getAllData.Lng),
map : map
});
}
我错过了什么吗?还是我的代码有问题?我是 Codeigniter 的新手,所以任何帮助都可以。谢谢!:D
编辑:在模型中返回可能的输出时,我已经完成了 json_encode,就像这里的那个一样。我想弄清楚为什么它没有在 div 中显示结果。
解决方案
您可以使用我测试过的这段代码。
$tbl_loc = $this->db->get('tbl_loc')->result_array();
return json_encode($tbl_loc);
推荐阅读
- php - 在 HTML 中格式化 PHP 回显
- python - 如何在 Jupyter 中使用 tqdm 进度条?
- php - 如何显示来自 JSON 文件 URL 的图像(本地主机存储)
- listview - QML ListView 中带有可拖动项目的延迟滚动
- haskell - 在 Haskell 类型签名中作为约束变量列出?
- azure-sdk-.net - Azure 管理服务的 Azure SDK - 端口和 IP
- c++ - 如何解决CSocket中发送后只能接收一个字符的问题
- python - Django/CSS:我正在尝试制作侧边栏,但是当我运行网站时它的标题,我做错了什么?
- sql-server - 扩展事件 - 不显示日志文件增长
- html - 已分配 UL 和 LI 时的要点