我需要创建一个html页面,从网站上获取json数据并显示它。
目前我的代码是这样的,显然不能按照我想要的方式完成工作,但我想要一个起点来显示页面信息。任何人都可以解释我怎么能这样做?
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Click Button to display information!</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
答案 0 :(得分:2)
所以你可以这样做:
此链接将向您展示如何更详细地操作:http://jsfiddle.net/9zfHE/8/
$(document).ready(function(){
$("#button").click(function(){
$.getJSON("http://example.com/",function(result){
$.each(result, function(i, field){
$("#myDiv").append("<tr id='bord'><td>"+i + "</td><td> " + field.name + "</td><td>" + field.description + "</td></tr>");
});
});
});
});
此链接正如您所希望的那样:http://jsfiddle.net/9zfHE/10/
$(document).ready(function(){
$("#button").click(function(){
$.getJSON("http://example.com/",function(result){
$.each(result, function(i, field){
$("#myDiv").append("<h4>" + field.name + "</h4><p>" + field.description + "</p>");
});
});
});
});
你必须使用ajax&amp; 。getJSON
方法基本上从网址抓取字段。然后我附加了一个从json到div的数据表。
如果你向json添加更多数据,那么你可以通过field.[json-field-name]
抓住它,并通过提供“id”来提供你喜欢的任何风格。它和它然后在CSS中造型。 i
跟踪json文件中的元素数量。
希望这有帮助
有关http://api.jquery.com/jquery.getjson/
的更多文档 Ajax
使用了一个jquery插件,该插件需要嵌入到您的页面中才能使用.getJSON
方法。
[编辑:]这就是你的html文件的样子:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#button").click(function(){
$.getJSON("http://example.com/",function(result){
$.each(result, function(i, field){
$("#myDiv").append("<h4>" + field.name + "</h4><p>" + field.description + "</p>");
});
});
});
});
</script>
</head>
<body>
<div id="myDiv"><h2>Click Button to display information!</h2></div>
<input type="submit" id="button" value="Change Content"></input>
<div></div>
</body>
</html>