2014-05-18 67 views
2

我需要创建一个html页面,该页面从网站获取json数据并显示它。从URL获取JSON数据并在HTML中显示

目前我的代码是这样的,这显然不按照我想要的方式完成工作,但我想要一个起点来显示页面中的信息。任何人都可以解释我可以如何去做这件事?

<!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> 

回答

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 &。 getJSON基本上从url中抓取字段的方法。然后我附加了一个从你的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> 
+0

哇!多谢老兄! 我想我现在得到它:D – MeyJaX

+0

我编辑了OP到我认为应该用你的例子看它应该看起来(稍后将自己修改它),抱歉再次打扰你,但我仍然有点困惑最终的结果应该如何看待。 – MeyJaX

+0

查看我的编辑请 – fscore

相关问题