【发布时间】:2015-06-08 08:31:33
【问题描述】:
我在http://www.w3schools.com/json/json_example.asp 中阅读了示例。
我尝试使用我的 MySQL 数据库和我的 PHP 代码。但它不起作用。 我是初学者,我不知道它出了什么问题。
这是我的 PHP 链接:http://xebus2014.tk/demo.php
我像这样更改 w3school 代码:
<!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>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xebus2014.tk/demo.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].STT +
"</td><td>" +
arr[i].ID +
"</td><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Singer +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
【问题讨论】:
-
同时发布您的 php 代码。不要将 php 放在 sn-p 中(因为它不起作用)
-
你的错误信息是什么
-
您不需要解析响应,因为它已经是 JSON。这可能是错误。
-
我执行了代码,它工作正常。我使用 PHP 如下
-
你的代码没问题,但是如果页面不是来自同一个域xebus2014.tk你可能会遇到跨域问题,除非你实现了CORS
标签: javascript php mysql json