使用Javascript读写Google电子表格单元格源。

4
我尝试使用JavaScript通过HTTP请求读取和写入Google电子表格中的单元格。 “读取”操作有效,但“写入”操作失败。 请帮忙指出哪个部分需要修改我的“写入”操作代码。
我遵循的写入示例来自这里https://developers.google.com/google-apps/spreadsheets/,但它没有起作用。
我的读取操作(有效):
http_request.onreadystatechange = function() {
    process_cellrw(http_request);
};
http_request.open('GET',"https://spreadsheets.google.com/feeds/cells/0Aqed....RHdGc/od6/private/full/R1C1", true);
http_request.setRequestHeader('Authorization','Bearer ' + strAccessToken);
http_request.send(null);

我的写入操作(这个不起作用):
var testxml =  ['&lt;entry xmlns="http://www.w3.org/2005/Atom" <br>
    xmlns:gs="http://schemas.google.com/spreadsheets/2006"&gt;',<br>
    '&lt;id>https://spreadsheets.google.com/feeds/cells/0Aqed....RHdGc/od6/private/full/R1C1&lt;/id&gt;',<br>
    '&lt;link rel="edit" type="application/atom+xml"<br> href="https://spreadsheets.google.com/feeds/cells/0Aqed....RHdGc/od6/private/full/R1C2/9zlgi"/&gt;',<br>
    '&lt;gs:cell row="1" col="1" inputValue="xxxx"/&gt;',<br>
    '&lt;/entry&gt;'].join('');<br>

http_request.onreadystatechange = function() {
    process_cellrw();
};

http_request.open('PUT',"https://spreadsheets.google.com/feeds/cells/0Aqed....RHdGc/od6/private/full/R1C2/9zlgi");
http_request.setRequestHeader('Authorization','Bearer ' + strAccessToken);
http_request.setRequestHeader('GData-Version','3.0');
http_request.setRequestHeader('Content-Type', 'application/atom+xml');
http_request.setRequestHeader('If-Match','*');
http_request.setRequestHeader('Content-Length', testxml.length.toString());
http_request.send(testxml);

写操作总是在回调函数 process_cellrw() 中收到 http_request.status = 0

我的环境是 Windows 7 + Chrome 浏览器。我还在 Android + Webkit 上进行了测试,仍然失败。

我还尝试通过列表提要添加一行,但收到 http_request.status = 0 而失败。

2个回答

0

我知道这并不是你问题的答案,但我建议你打开Chrome的“开发者工具”,进入“网络”选项卡,检查Google API调用的响应。它可能包含了解失败原因的头信息...


是因为XMLHttpRequest不支持跨域HTTP PUT请求吗?http_request是一个XMLHttpRequest对象。 - Jeffrey Xuan

0

我找到了根本原因:docs.googole.com和spreadsheets.google.com不支持跨域XMLHttpRequest POST/PUT。

XMLHttpRequest POST/PUT将首先向其他域上的资源发送HTTP OPTIONS请求头,以确定实际请求是否安全。但是docs.googole.com和preadsheets.google.com始终回复“404 Not Found”此请求。这就是为什么我总是在回调函数process_cellrw()中收到http_request.status = 0的原因。

一种解决方案是使用另一个允许跨域HTTP请求的CGI,例如PHP。 另一种解决方案是使用函数UrlFetchApp来实现写操作,以发送HTTP PUT请求Google Apps Script,然后我们可以使用XMLHttpRequest GET触发此Apps Script。


4
你能发布一下你的解决方案吗?我遇到了相同的问题,不知道如何实现你的变通方法。 - Josh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接