从 Google 文档获取数据到 Javascript

Getting data from Google docs into Javascript

我尝试从 google 电子表格中获取数据,当我在本地测试 html 页面时一切正常。但是当我将 html 文件和 javascript 文件加载到服务器时,没有任何效果。

这里是 html 文件的代码 "page.htm":

<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body
onload= "Data();">
<table>             
    <form name="Team">
    <tr>                
        <td>
        <input  size="19"  name="tName" readonly >
        </td>               
    </tr>
    </form>
    </table>
</body>
</html>

和js文件"teams.js":

function Data() {
var url="https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";

xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status==200){
      document.Team.tName.value = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}

Google doc

当我 运行 代码工作时,用 csv 文件值填充输入。当我尝试 运行 时,How do you Import data from a Google Spreadsheet to Javascript? 上的 link 从我的浏览器中获得了跨源块。

如果您不能 运行 下面的脚本,您应该尝试在您的浏览器上允许 CORS,或者尝试使用 ajax.load 来获取文件。

<html>

<head>
  <title>
  </title>
  <script type="text/javascript">
    function Data() {
      var url = "https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";

      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          document.Team.tName.value = xmlhttp.responseText;
        }
      };
      xmlhttp.open("GET", url, true);
      xmlhttp.send(null);
    }
  </script>
</head>

<body onload="Data();">
  <table>
    <form name="Team">
      <tr>
        <td>
          <input size="19" name="tName" readonly>
        </td>
      </tr>
    </form>
  </table>
</body>

您应该会看到类似这样的内容:

在我自己的服务器上试过 - 在浏览器的控制台上出现以下 CORS 错误:

这意味着您无法使用浏览器直接访问 url,因为 Google 的服务器未发回允许此操作的必需 header 字段。

解决此问题的方法是使用替代方案 API,它可以为我们提供 Google 电子表格的 JSONP 格式输出:

所以考虑这个 JavaScript:

function Data(response) {
  document.Team.tName.value = response.feed.entry[0].gs$cell.$t;
}

以及以下HTML:

<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body>
<table>             
    <form name="Team">
    <tr>                
        <td>
        <input  size="19"  name="tName" readonly >
        </td>               
    </tr>
    </form>
    </table>
<script src="https://spreadsheets.google.com/feeds/cells/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/1/public/values?alt=json-in-script&callback=Data&range=A1"></script>
</body>
</html>

它应该可以完美运行。

这不是您赢得的代码,而是 Google 自己的服务器使用正确的数据调用 Data 函数 - 一种称为 JSONP 的方法允许 cross-domain 数据请求。默认情况下,浏览器会阻止从另一个域请求数据。唯一的例外是 file:// 协议,它允许对任何域的一些请求,因为没有匹配规则的源域。这就解释了为什么你的代码在本地可以运行,但是上传到服务器后就不行了。