我必须检索 Json 中的数据,然后将其显示在表格中。我尝试了几种方法,但没有成功。这是我的这个函数的代码,有人可以帮助我找出这个代码有什么问题,因为我没有显示任何内容,也没有错误。谢谢您
代码已更新。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1>display the menu</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
var html = "<table border='1|1'>";
for (var i = 0; i < obj.response.length; i++) {
html+="<tr>";
html+="<td>"+obj.response[i].id+"</td>";
html+="<td>"+obj.response[i].restaurant_id+"</td>";
html+="<td>"+obj.response[i].name+"</td>";
html+="</tr>";
}
html+="</table>";
$("div").html(html);
}
};
xhttp.open("GET", "http://deleted url sorry", true);
xhttp.send();
}
</script>
</body>
</html>
我必须检索 Json 中的数据,然后将其显示在表格中。我尝试了几种方法,但没有成功。这是我的这个函数的代码,有人可以帮我找出这段代码有什么问题吗?谢谢
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1>display the menu</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
var obj = JSON.parse(this.responseText);
//document.getElementById("demo").innerHTML = obj.response[0].id + " " + obj.response[0].restaurant_id + " "+ obj.response[0].name;
}
var count = 0;
var html = "<table border='1|1'>";
for (var k in obj) {
if (obj.hasOwnProperty(k))
{ ++count; }
//document.getElementById("demo").innerHTML = obj.response[count].id + " " + obj.response[count].restaurant_id + " "+ obj.response[count].name;
html+="<tr>";
html+="<td>"+obj.response[count].id+"</td>";
html+="<td>"+obj.response[count].restaurant_id+"</td>";
html+="<td>"+obj.response[count].name+"</td>";
html+="</tr>";
}
html+="</table>";
$("div").html(html);
};
xhttp.open("GET", "the URL I deleted it when posting", true);
xhttp.send();
}
</script>
</body>
</html>
感谢您的帮助。
最佳答案
当您执行 $('div').html() .... 页面中不存在 div 元素,因此不会呈现任何内容
关于javascript - 无法使用 json 对象通过 Javascript 显示动态表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40905368/