【问题标题】:access the response Json data in javascript在 javascript 中访问响应 Json 数据
【发布时间】:2019-02-20 10:24:52
【问题描述】:

我在我的 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' 元素中吗? 任何帮助将不胜感激

【问题讨论】:

  • success: function (data) { 之后使用console.log(data) 并向我们展示结果?同时显示 generation_date 元素。
  • 我认为 $output 是一个数组,也许您需要使用所需值的索引来访问?喜欢data.certInfo[0].timestamp
  • 你试过吗。 $.parseJSON(data) ?
  • @MorganFreeFarm 抱歉,日志打印在哪里?检查浏览器的一部分?
  • @ShakibKarami 按 f12 显示控制台

标签: javascript php html json ajax


【解决方案1】:

在您的 PHP 中,$output 似乎是一个数组。所以在你的javascript中你需要访问好的索引来获取数据。

试试:

 document.getElementById("generation_date").textContent = data.certInfo[0].timestamp;
 ----------------------------------------------------------------------^^^

【讨论】:

  • @ShakibKarami 点赞 MorganFreeFarm 评论,我们需要成功函数开头的consol.log(data) 的内容来帮助你
  • 对不起,我错了 certInfo 是一个数组 :) 非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 2019-10-08
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多