gpt4 book ai didi

javascript - 如何将动态数据从 JSON 获取到 jvqmaps 作为对象而不是来自 php mysqli 的数组

转载 作者:行者123 更新时间:2023-11-29 21:14:26 25 4
gpt4 key购买 nike

sibling 们大家好

我的第一篇文章,我是 json 新手,在将数据导入 jvqmap 时遇到问题,如果我只添加一个 var ie 就可以让它工作

var sample_data = ({
"gb":"6","us":"3"
});

但不是动态的,我认为需要传递一个对象,因为入站数据在控制台中显示为 json 数组,只是一种预感,但不知道如何使用 ajax 来做到这一点。下面的 json 响应。如果有人可以提供帮助,我将永远感激不已,1 年 php 没有真正突破芥末。

  $.ajax({
url: 'countries.php',
dataType: 'json',
success: function(json) {

data = [];

for (i in json) {
data[i] = json[i];
}
// var data = JSON.parse(json);
console.log(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" +

xhr.responseText);
}
});
jQuery('#vmap').vectorMap({

map: 'world_en',
backgroundColor: null,
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
selectedRegions: [],
values: data_arr
,

onLabelShow: function (event, label, code) {

if(data[code] > 0)
label.append(': '+data[code]+' Attendees');
} });

Countries.php 页面

header('Content-type: application/json');
$conn = new mysqli("localhost", "root", "", "wordpress2");
//$result = $conn->query("
$query = "SELECT * from countries";
//MySQL query

$json = array();

$result = $conn->query($query); //MySQL query is executed, and result stored in the variable $result

while($row = $result->fetch_assoc()){ //the result is an associate array, this array is assigned to $row variable

$json[] = $row['CNT_ISO'].'"'. ':'. '"' .$row['attendees'] ;

最佳答案

要生成一个与您手动创建的测试对象类似的对象,您可以创建一个 stdClass() 对象,用所需的数据填充其属性,然后通过调用 json_encode( ) 在您的对象上,它将自动转换为 JSON 字符串以传递回 javascript。

您还可以通过仅从查询中返回您实际想要的内容来提高查询效率。

在任何查询调用后添加一些状态检查也是一个好主意。

$conn = new mysqli("localhost", "root", "", "wordpress2");

$query = "SELECT CNT_ISO, attendees from countries";

$result = $conn->query($query);
if ( $result === FALSE ) {
echo $conn->error;
exit;
}

$countries = new stdClass() // create a new object

while($row = $result->fetch_assoc()){
$countries->{$row['CNT_ISO']} = $row['attendees'];
}
echo json_encode($countries);

关于javascript - 如何将动态数据从 JSON 获取到 jvqmaps 作为对象而不是来自 php mysqli 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083539/

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