我正在构建Chrome扩展程序,该扩展程序应该编辑Google电子表格中的单元格。我设法读取工作表内容但无法编辑单元格。目前我的错误是“400(错误请求)”。知道我在这里做错了吗?
我在此处查看了Google表格API文档和其他已发布的问题,但无法找到任何解决方案。
以下是我用来获取工作表内容的代码(这可行):
function loadSpreadsheet(token) {
var y = new XMLHttpRequest();
y.open('GET', 'https://spreadsheets.google.com/feeds/list/1NE8g7kyk-Z6Sci9_w6mdY2KV8542a3TJd9lIbucHZiU/default/private/values?access_token=' + token);
y.onload = function() {
console.log(y.response);
};
y.send();
}
这是我尝试编辑(PUT)新单元格的代码(给我“400 - 错误请求”):
function add_title(message, token) {
url = 'https://spreadsheets.google.com/feeds/cells/1NE8g7kyk-Z6Sci9_w6mdY2KV8542a3TJd9lIbucHZiU/default/private/full/cell?access_token=' + token;
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006">',
'<id>https://spreadsheets.google.com/feeds/cells/1NE8g7kyk-Z6Sci9_w6mdY2KV8542a3TJd9lIbucHZiU/default/private/full/R2C4</id>',
'<link rel="edit" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/1NE8g7kyk-Z6Sci9_w6mdY2KV8542a3TJd9lIbucHZiU/default/private/full/R2C4"/>',
'<gs:cell row="2" col="4" inputValue="',foo,'"/>',
'</entry>'].join('');
return atom;
};
var params = constructAtomXML(message);
var z = new XMLHttpRequest();
z.open("PUT", url);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.send(params);
}
答案 0 :(得分:0)
在评论的帮助下,我终于明白了:我必须将 OAuth 和 If-Match 添加到请求的标题中。
最终代码应如下所示:
function add_title(token, message) {
url = 'https://spreadsheets.google.com/feeds/cells/1NE8g7kyk-Z6Sci9_w6mdY2KV8542a3TJd9lIbucHZiU/default/private/basic/R2C4?access_token=' + token;
function constructAtomXML(foo){
var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006">',
'<id>https://spreadsheets.google.com/feeds/cells/key/private/basic/R2C4</id>',
'<link rel="edit" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/key/default/private/basic/R2C4"/>',
'<gs:cell row="2" col="4" inputValue="' + foo + '"/>',
'</entry>'].join('');
return atom;
};
var params = constructAtomXML(message);
var z = new XMLHttpRequest();
z.open("PUT", url);
z.setRequestHeader("Content-type", "application/atom+xml");
z.setRequestHeader("GData-Version", "3.0");
z.setRequestHeader("Authorization", "GoogleLogin auth=" + token);
z.setRequestHeader("If-Match", "*");
z.send(params);
}