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);

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

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

我还测试了按列表提要添加一行,也通过接收失败http_request.status = 0

4

2 回答 2

0

我知道这不能回答您的问题,但我会打开 Chrome 的“开发者工具”,转到“网络”并检查来自谷歌的 API 调用响应。它可能包含解释失败原因的标题...

于 2012-11-08T22:02:42.523 回答
0

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

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

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

于 2012-11-15T14:28:39.203 回答