从 Java 脚本访问没有 table ID 的外部网页 HTML table 并转换为 JSON

Access External webpage HTML table without table ID from Java Script and convert to JSON

我写了一个脚本来获取 HTML table 数据到 JSON 对象。

为此我使用了 lightswitch05 jquery 插件。

在这段代码中,我可以在 Javascript 的同一网页中访问 HTML table 数据 使用

var table = $('#example-table').tableToJSON();

但我需要访问外部网页HTML table。 Table URL 在这里 - http://ccmcwolf.byethost4.com/index.html

如何将它更改为上面的“#example-table”到外部网页 table?

<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script
src="http://lightswitch05.github.io/table-to-json/javascripts/jquery.tabletojson.min.js">
</script>
<script>
function myFunction() {
   var table = $('#example-table').tableToJSON();
  console.log(table);
  alert(JSON.stringify(table));  
    }
$(document).ready(myFunction);
</script>
</head>
<body>
<table id='example-table' class="table table-striped">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th data-override="Score">Points</th></tr>
  </thead>
  <tbody>
    <tr>
      <td>Jill</td>
      <td>Smith</td>
      <td data-override="disqualified">50</td></tr>
    <tr>
      <td>Eve</td>
      <td>Jackson</td>
      <td>94</td></tr>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>80</td></tr>
    <tr>
      <td>Adam</td>
      <td>Johnson</td>
      <td>67</td></tr>
  </tbody>
</table>
</body>
</html> 

非常感谢!

因为 JavaScript 只在当前页面有范围(即它可以访问和修改它嵌入的页面的内容或 declared/linked 使用脚本标签),我不不认为有任何直接的方法。

但是如果该外部页面与当前 JavaScript 代码运行的域相同,您始终可以通过对服务器的 Ajax 调用来获取 html,然后运行 您的代码以 JSON 形式提取 html table。

如果我遗漏了什么,请告诉我,我会根据您的意见编辑我的答案。

谢谢。