我在我的 HTML 中使用 Json 从数据库获取数据,但我无法访问返回的 Json 的数据,这里是我的 HTML 函数:
$.ajax({
type: "POST",
url: 'fetch.php',
dataType: 'json',
data: {func:"viewCert",tracking_code:tracking_code},
success: function (data) {
if (data!=null) {
document.getElementById("generation_date").textContent = data.certInfo.timestamp;
} else {
alert("Something's Wrong! Try Later");
window.location = "../views/failed.html";
}
}
});
这里是 fetch.php 函数:
function viewCert($tracking_code) {
$connect = connection();
$connect->set_charset("utf8");
$sql = "SELECT timestamp FROM certificate WHERE tracking_code=?";
$result = $connect->prepare($sql);
$result->bind_param("s",$tracking_code);
$result->execute();
$res=$result->get_result();
while ($row=$res->fetch_object()) {
$output[]=$row;
}
echo json_encode(array('certInfo' => $output));
}
对于这个问题,我很抱歉,我只是 HTML 和 Javascript 的新手,所以有人知道为什么不在“generation_date”元素中设置时间戳吗? 任何帮助将不胜感激
最佳答案
在您的 PHP 中,$output
似乎是一个数组。因此,在您的 JavaScript 中,您需要访问良好的索引以获取数据。
尝试:
document.getElementById("generation_date").textContent = data.certInfo[0].timestamp;
----------------------------------------------------------------------^^^
关于javascript - 在 javascript 中访问响应 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784022/