首页 > 解决方案 > 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 中显示结果。

标签: javascriptphpcodeignitermaps

解决方案


您可以使用我测试过的这段代码。

$tbl_loc = $this->db->get('tbl_loc')->result_array();
return json_encode($tbl_loc);

推荐阅读