我正在尝试通过 php -> json -> ajax 将 mysql 数据获取到 Chartjs 的 JS 变量中。php 生成的 JSON 看起来非常好。不幸的是,当试图在我的变量中获取数据时,控制台将它们返回为未定义。这是我的代码:<?php$con=mysqli_connect("---");// Check connectionif (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}$result = mysqli_query($con,"SELECT clanarina, vakufnama, zekjat, year from payments where uid = 1");$data = array();foreach ($result as $row) { $data[] = $row;}$result->close();mysqli_close($con);print json_encode($data);?>JSON: [{"clanarina":"240","vakufnama":"12500","zekjat":"0","year":"2019"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2021"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2022"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2023"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2024"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2025"}]控制台输出:[{"clanarina":"240","vakufnama":"12500","zekjat":"0","year":"2019"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2021"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2022"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2023"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2024"},{"clanarina":"240","vakufnama":"0","zekjat":"0","year":"2025"}] chart-bar-demo.js:10:15Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]chart-bar-demo.js:22:15Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]chart-bar-demo.js:23:15Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]chart-bar-demo.js:24:15如您所见,console.log(data) 也可以正常工作,但将数据推送到变量中似乎是个问题。
1 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
PHP 返回的 JSON 在您推入数组时仍然是一个字符串。您会注意到数组长度对应于字符串的长度。
您需要在循环之前将 JSON 字符串解析为 JS 数组,您可以使用JSON.parse();
- 1 回答
- 0 关注
- 85 浏览
添加回答
举报
0/150
提交
取消