【问题标题】:Take JSON data from URL and display in HTML从 URL 获取 JSON 数据并以 HTML 显示
【发布时间】:2014-05-18 14:10:07
【问题描述】:

我需要创建一个 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>

【问题讨论】:

    标签: json xmlhttprequest


    【解决方案1】:

    所以你可以这样做:

    此链接将向您展示如何更详细地操作: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>
    

    【讨论】:

    • 哇!非常感谢哥们!我想我现在明白了:D
    • 我使用您的示例将 OP 编辑​​为我认为的外观(稍后我会自己修改),很抱歉再次打扰您,但我仍然对结尾的方式有点困惑结果应该看起来。
    • 刚刚做到了!再次感谢您的帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2020-05-03
    • 2012-07-12
    • 2013-08-24
    • 2013-03-10
    • 2018-10-10
    相关资源
    最近更新 更多