我已经编写了这段代码,但它不起作用。我很确定它大部分是正确的,但我不知道它有什么问题。脚本返回输出“undefined”
------ PHP ON SERVER -----------------(http://www.autofficinacicco.it/json.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli($nomehost, $nomeuser, $password, "");
$result = $conn->query("SELECT codice, immagine, testo FROM Promozioni");
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[]=$rs;
}
$conn->close();
echo json_encode($outp);
?>
----- JAVA SCRIPT ----------------------------------------
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.autofficinacicco.it/json.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+=arr["immagine"];
out+="</br>";
out+=arr["codice"];
out+="</br>";
out+=arr["testo"];
out+="</br>";
}
out += "</table>"
document.getElementById("id").innerHTML =out;
}
</script>
答案 0 :(得分:2)
您的JSON不是正确的文档。更改json格式并使用json_encode();功能
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Codice":"' . $rs["codice"] . '",';
$outp .= '"Testo":"' . $rs["testo"] . '",';
$outp .= '"Immagine":"'. $rs["immagine"] . '"}';
}
$outp .="]";
$conn->close();
到
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[] = $rs;
}
$conn->close();
echo json_encode($outp);