猿问

JSON 到 JavaScript 变量通过 AJAX 和 PHP MYSQL =>

我正在尝试通过 php -> json -> ajax 将 mysql 数据获取到 Chartjs 的 JS 变量中。php 生成的 JSON 看起来非常好。不幸的是,当试图在我的变量中获取数据时,控制台将它们返回为未定义。


这是我的代码:


<?php


$con=mysqli_connect("---");

// Check connection

if (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:15


Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]

chart-bar-demo.js:22:15


Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]

chart-bar-demo.js:23:15


Array(385) [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, … ]

chart-bar-demo.js:24:15

如您所见,console.log(data) 也可以正常工作,但将数据推送到变量中似乎是个问题。


holdtom
浏览 86回答 1
1回答

收到一只叮咚

PHP 返回的 JSON 在您推入数组时仍然是一个字符串。您会注意到数组长度对应于字符串的长度。您需要在循环之前将 JSON 字符串解析为 JS 数组,您可以使用JSON.parse();
随时随地看视频慕课网APP
我要回答