首页 > 解决方案 > 如何从html中的url获取json数据

问题描述

我正在尝试从以下位置获取 json 数据:https ://www.topurbanaradio.com/ps/scast.php

我尝试使用几个对其他人有用的代码,但我无法从 URL 中获取任何信息。

我尝试的最后一个代码是这个:

$(function() {
  var entries = [];
  var JSONurl = "https://www.topurbanaradio.com/ps/scast.php";
  $.getJSON(JSONurl, function(data) {
    $.each(data.entries, function(i, f) {
      var tblRow = "<tr>" + "<td>" + f.cancion + "</td>" + "<td>" + f.artista + "</td>" + "<td>" + f.almbumart + "</td>" + "</tr>"
      $(tblRow).appendTo("#entrydata tbody");
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<body>
  <div class="wrapper">
    <div class="profile">
      <table id="entrydata" border="1">
        <thead>
          <th>Artista</th>
          <th>Cancion</th>
          <th>AlbumArt</th>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
  </div>
</body>

标签: javascripthtmljson

解决方案


tbody中为您的表添加tr并为您从. 然后将结果附加到tr我还建议在结果显示时使用加载器。$eachapi

使用CORS 扩展打开它

注意:我使用的是 firefox + CORS

$(function() {
  var entries = [];
  var JSONurl = "https://www.topurbanaradio.com/ps/scast.php";
  $.getJSON(JSONurl, function(data) {
    $.each(Object.values(data), function(i, value) {
      console.log(value)
      var tblRow = "<td>" + value + "</td>"
      $(tblRow).appendTo("#entrydata tbody tr");
    });

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<body>
  <div class="wrapper">
    <div class="profile">
      <table id="entrydata" border="1">
        <thead>
          <th>Artista</th>
          <th>Cancion</th>
          <th>AlbumArt</th>
        </thead>
        
        <tbody>
        <tr></tr>
        </tbody>
      </table>
    </div>
  </div>
</body>


推荐阅读