1

我正在尝试使用 JSON 从我的数据库中检索数据并在表中解析它们。

目前我这样检索它:

xmlhttp = new XMLHttpRequest()

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var jsontext = xmlhttp.responseText;
        var json = JSON.parse(jsontext);

        console.log(json.service)

    }
}

xmlhttp.open("GET", "mysql.php?p=getservice" + "&carid=" + "KYF111", true);
xmlhttp.send();

这会给我一个结果,无论我有多少行 id 'term'。

我的 mysql.php 文件如下所示:

case 'getservice':

$q = mysql_real_escape_string($_GET['q']);
$carid = stripslashes($_GET['carid']);
$query = "SELECT * FROM Service WHERE carid = '".$carid."'";

$result = mysql_query($query);

$json = array();
while ($row = mysql_fetch_array($result)) {

    $json['carid'] = $row['carid'];
    $json['service'] = $row['service'];
    $json['date'] = $row['date'];
    $json['nextdate'] = $row['nextdate'];
    $json['kilometers'] = $row['kilometers'];
    $json['servicedby'] = $row['servicedby'];
    $json['invoice'] = $row['invoice'];
    $json['cost'] = $row['cost'];
    $json['remarks'] = $row['remarks'];

}
print json_encode($json);

mysql_close();

break;

这是我的数据库的样子:

在此处输入图像描述

所以该术语将是 cardid,我想要包含 carid 术语的行中的所有值。然后单行上的每个值都在 a 之间。像这样的东西:

<tbody>
    <tr>
        <td>Tyre</td>
        <td>10-10-2012</td>
        <td>31-10-2012</td>
        <td></td>
        <td>George</td>
        <td>8951235</td>
        <td>0</td>
        <td>Lorem Ipsum</td>
    </tr>
    <tr>
        <td>Lights</td>
        <td>17-10-2012</td>
        <td>23-10-2012</td>
        <td></td>
        <td>Antony</td>
        <td>4367234</td>
        <td>0</td>
        <td>Lorem Ipsum</td>
    </tr>
</tbody>
4

2 回答 2

1

您的while循环每次都覆盖相同的数组条目,而不是制作一个二维数组。它应该是:

$json = array();
while ($row = mysql_fetch_array($result)) {
  $json[] = $row;
}
echo json_encode($json);

在您的 JavaScript 中,您需要遍历返回的数组。而不是console.log(json.service)它应该是:

for (var i = 0; i < json.length; i++) {
    console.log(json[i].service);
}
于 2012-10-20T05:13:06.183 回答
1

试试这样:

    $temp=0;
    $json = array();
        while ($row = mysql_fetch_array($result)) {

            $json[$temp]['carid'] = $row['carid'];
            $json[$temp]['service'] = $row['service'];
            $json[$temp]['date'] = $row['date'];
            $json[$temp]['nextdate'] = $row['nextdate'];
            $json[$temp]['kilometers'] = $row['kilometers'];
            $json[$temp]['servicedby'] = $row['servicedby'];
            $json[$temp]['invoice'] = $row['invoice'];
            $json[$temp]['cost'] = $row['cost'];
            $json[$temp]['remarks'] = $row['remarks'];
    $temp++;
        }
print json_encode($json);
于 2012-10-20T05:14:22.530 回答