图像不在json页面中显示

时间:2016-07-04 13:54:30

标签: javascript php json

来自数据库的图像不会出现在json页面和html页面中,而是输出图像源名称。如何在html页面上显示图像?

感谢您宝贵的时间。

linejson.php页面

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "db_user", "db_pwd", "db_name");

$result = $conn->query("SELECT tbl_users.image, tbl_users.firstname, tbl_users.lastname, tbl_users.username,    tbl_posts.post, tbl_posts.post_date
                    FROM tbl_posts INNER JOIN tbl_users ON  tbl_users.id=tbl_posts.user_id
                    WHERE tbl_posts.user_id=3");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}

$outp .= '{"Image":"'  . $rs["image"] . '",';
$outp .= '"Firstname":"'   . $rs["firstname"]     . '",';
$outp .= '"Lastname":"'  . $rs["lastname"] . '",';
$outp .= '"Username":"'   . $rs["username"]        . '",';
$outp .= '"Post":"'   . $rs["post"]        . '"}';

}
$outp .="]";

$conn->close();

echo($outp);
?>

linejson.html页面

<!DOCTYPE html>
<html>

<head>
<style>

 table, th , td  {
 border-top: 1px solid purple;
 border-collapse: collapse;
 padding: 15px;

}
table tr:nth-child(odd) {
background-color: #f0f1f1;

}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>

<body>
<div id="timeline"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.outpaceng.com/linejson.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].Image +
    "</td><td>" +
    arr[i].Firstname +
    "&nbsp;" +
    arr[i].Lastname +
    "&nbsp;" +
    arr[i].Username +
    "<br>" +
    arr[i].Post +
    "</td><tr>" ;

   }
   out += "</table>";
   document.getElementById("timeline").innerHTML = out;
 }
 </script>

</body>
 </html>

1 个答案:

答案 0 :(得分:1)

代码可以被sipmlified,你应该使用json_encode来创建json

更改此

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}

$outp .= '{"Image":"'  . $rs["image"] . '",';
$outp .= '"Firstname":"'   . $rs["firstname"]     . '",';
$outp .= '"Lastname":"'  . $rs["lastname"] . '",';
$outp .= '"Username":"'   . $rs["username"]        . '",';
$outp .= '"Post":"'   . $rs["post"]        . '"}';

}
$outp .="]";

$conn->close();

echo($outp);

echo json_encode($result->fetch_all());
$conn->close();

和JavaScript

for(i = 0; i < arr.length; i++) {
    out += "<tr><td><img src='" +
    arr[i].image +
    "' alt="img"/></td><td>" +
    arr[i].firstname +
    "&nbsp;" +
    arr[i].lastname +
    "&nbsp;" +
    arr[i].username +
    "<br>" +
    arr[i].post +
    "</td><tr>" ;
}