我正在学习JSON并且必须尝试获得这个示例我发现在我的网站上工作但是当我使用它检索4个或更多列而不是示例中的三个对我来说工作正常时会遇到麻烦。 php文件:
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "***", "****", "inventory_form");
$result = $conn->query("SELECT FName, LName, Eqpmnt_Brwd, Service_Tag FROM Inventory");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"FirstName":"' . $rs["FName"] . '",';
$outp .= '"LastName":"' . $rs["LName"] . '",';
$outp .= '"Eqpmnt_Brwd":"'. $rs["Eqpmnt_Brwd"] . '",';
$outp .= '"ServiceTag":"'. $rs["Service_Tag"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
和html文件:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>SHS Inventory Form</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "inventory_table.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].FirstName +
"</td><td>" +
arr[i].LastName +
"</td><td>" +
arr[i].Eqpmnt_Brwd +
"</td><td>";
arr[i].ServiceTag +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
response.txt包含Service_Tag信息:
"[{"FirstName":"George","LastName":"****r","Eqpmnt_Brwd":"Laptop","ServiceTag":"075247"},{"FirstName":"Nadine","LastName":"****n","Eqpmnt_Brwd":"Apple Video Dongle","ServiceTag":""},{"FirstName":"Nicole ","LastName":"*****o","Eqpmnt_Brwd":"Hovercam","ServiceTag":"075642"} etc...
但是用firebug检查页面上的HTML我发现该列是空白的:
<div id="id01">
<table>
<tbody>
<tr>
<td>George</td>
<td>O****</td>
<td>Laptop</td>
<td></td>
</tr>
我已将代码通过JSON Lint和ok,一个php验证器确定并检查我的MySQL语句确定但仍然在任何第三列之后我无法读出任何内容。我知道它可能很简单,但我已经盯着这一段时间没有回答了。
答案 0 :(得分:0)
如果有人有兴趣,我会遇到语法错误:
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].FirstName +
"</td><td>" +
arr[i].LastName +
"</td><td>" +
arr[i].Eqpmnt_Brwd +
"</td><td>" +
arr[i].ServiceTag +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;