【问题标题】:Able to access Google Spreadsheet in CSV format, but not JSON format?能够以 CSV 格式访问 Google 电子表格,但不能以 JSON 格式访问?
【发布时间】:2015-01-09 21:35:44
【问题描述】:

使用 Google 的 Visualization API,我正在尝试访问 Google 电子表格中的一行,其中该行在名为“key”的列中有一个给定的字符串。

当我使用此代码时,成功函数会触发,并且我的数据为 CSV 格式:

$( ".submit" ).click(function() {
    $.ajax({
                url: 'https://docs.google.com/spreadsheets/d/1VNr3_0uknNiZct948fPAnVn9mVfepKTqkprB1orS3eo/gviz/tq?tqx=out:csv&tq=select+B,C,D+where+B+matches+%27Osax5Gm8l3Ew3rXx%27&gid=0',
                type: 'GET',
                success: function(data) { console.log(data); },
                error: function(error) { console.log(error.statusText); }
        });
});

但是当我使用此代码时,only 更改为“tgx=out:json”,以便我获取 JSON 格式的数据,错误函数会触发。这有两个特别令人沮丧的方面:我的 statusText 给了我“OK”,而我的控制台中没有其他错误消息,所以我无法弄清楚错误是什么。此外,如果我在浏览器中查看这个 URL,我可以看到 JSON 代码很好——它只有在通过这个 ajax 请求使用时才会失败。

$( ".submit" ).click(function() {
    $.ajax({
                url: 'https://docs.google.com/spreadsheets/d/1VNr3_0uknNiZct948fPAnVn9mVfepKTqkprB1orS3eo/gviz/tq?tqx=out:json&tq=select+B,C,D+where+B+matches+%27Osax5Gm8l3Ew3rXx%27&gid=0',
                type: 'GET',
                success: function(data) { console.log(data); },
                error: function(error) { console.log(error.statusText); }
        });
});

【问题讨论】:

    标签: jquery ajax json google-sheets


    【解决方案1】:

    默认情况下,大多数现代浏览器都禁用跨域 javascript,除非端点服务器添加了专门允许它的标头。见Access-Control-Allow-Origin

    解决此问题的一种方法是在您自己的服务器上运行一些服务器端代码以充当代理。因此,您的 javascript 从托管页面的同一域中获取数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多