gpt4 book ai didi

javascript - 通过 PHP 将 mySQL 数据拉入 Javascript 对象数组

转载 作者:行者123 更新时间:2023-11-28 23:13:54 25 4
gpt4 key购买 nike

我正在尝试从 mySQL 中提取数据并将其转换为一种格式,然后我可以将其传递给 google.maps API。我认为 mySQL -> php -> javascript -> google.maps 最有意义,但我肯定会接受其他建议。

到目前为止,我已经连接并成功地将我的数据查询到一个数组中

<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');

//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}

//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";

if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}

//initialize an array to store data
$rows = array();

while ($data = $results->fetch_assoc()) {
$rows[] = $data;

echo "<br><br>Loop rotation: ";
var_dump($data);
}

echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>

现在我只需要将这些数据转换成可以传递给 google.maps 的可用数据。

之前我从文本文件中提取 JSON,这很有效,但我想要数据库的灵 active 和稳定性。很容易解析成 Javascript 对象数组。然后我可以调用我需要的索引和属性,正如你从我使用的这个函数中看到的那样。

function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){

//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};

//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}

感谢您对我的问题提供的任何帮助。

最佳答案

听起来您已经找到了答案,但为了完整起见,我会发布。

只需将 var_dump($rows) 行更改为 json_encode($rows)

阅读更多关于 json_encode 的信息在 php 文档中。

您可能想要两个 php 文件:

  • api.php 发出 Content-type: application/json
  • 的文件
  • index.php 发出 Content-type: text/html 并调用 api.php
  • 的文件

在索引页面上,您可以对 API 端点进行 AJAX 调用,然后使用 JSON.parse(response)

关于javascript - 通过 PHP 将 mySQL 数据拉入 Javascript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com