我正在尝试执行Google电子表格的doGet函数,以便从工作表中获取一些数据。数据必须在JSON对象中返回。现在,我在JSON对象中返回简单的虚拟内容,因为我还无法接收JSON对象并从中读取数据。
我有一个简单的doGet函数,它由一个HTML调用。
doGet函数包含一个count()函数,它对这个doGet函数的每个调用进行计数。这样我就知道,doGet是被执行的(这部分工作很好)。
function doGet(e){
//add +1 to value of a specific spreadsheet cell;
//count() always works, even though I don't get the JSON object.
count();
var content = {
"answer": "This is an answer",
"body" : "Welcome to the web app."
};
//convert JavaScript object into a string
//so that it can be sent
var JSONString = JSON.stringify(content);
var JSONOutput = ContentService.createTextOutput(JSONString);
JSONOutput.setMimeType(ContentService.MimeType.JSON);
return JSONOutput;
}
现在,我创建了一个HTML来调用这个doGet函数。我正在记录一些部分,看看实际执行了什么。
<html>
<head>
<title>Call GAPI</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="./jquery/jquery-3.3.1.min.js" type="text/javascript"></script>
<script>
console.log("Prepare API Call");
$(function(){
$.getJSON('https://script.google.com/macros/s/*encrpyted-URL*/exec?callback=?', function(json) {
var json = JSON.parse(result); //parsing is necessary because response is actually a TextOutput which needs to be turned into a javascript object
console.log(json.answer); //not executed
console.log("Done API Call"); //not executed
});
});
console.log("End");
</script>
</body>
</html>
大多数时候,我在控制台中看到这个:
Prepare API Call
End
所以,除了API调用之外,一切都是执行的。有时,我也会遇到CORB错误阻塞,这很奇怪,因为它并不总是出现在:
跨源读取阻塞(CORB)阻止跨原点响应=1548439425032与MIME类型text/html。有关更多详细信息,请参阅https://www.chromestatus.com/feature/5629709824032768。
它说我收到了一个文本/html的回复,这难道不奇怪吗?在doGet函数中,返回的对象被声明为JSON对象。然而,goGet返回一个TextOutput对象或字符串。所以它需要被解析..。我不知道为什么不能读取返回的JSON对象,也不知道为什么要得到CORB错误。有人能帮我吗?
还有一件事:只使用URL/exec调用“被CORS策略阻塞”;所以我需要添加URL/exec?callback=?来解决这个问题。
发布于 2019-01-26 01:43:27
如果我的理解是正确的,这次修改怎么样?我想你的处境可能有几个答案。所以,请把这看作是其中之一。
修改要点:
用于Google脚本端
ContentService.MimeType.JAVASCRIPT
来实现setMimeType
。createTextOutput
修改为e.parameter.callback + '(' + JSONString + ')'
。用于HTML端
result
of var json = JSON.parse(result)
。JSON.parse()
也不是必需的。修改脚本:
当以上要点反映到您的脚本中时,如下所示。
Google脚本端
发自:
var JSONOutput = ContentService.createTextOutput(JSONString);
JSONOutput.setMimeType(ContentService.MimeType.JSON);
至:
var JSONOutput = ContentService.createTextOutput(e.parameter.callback + '(' + JSONString + ')');
JSONOutput.setMimeType(ContentService.MimeType.JAVASCRIPT);
HTML侧
发自:
$.getJSON('https://script.google.com/macros/s/*encrpyted-URL*/exec?callback=?', function(json) {
var json = JSON.parse(result);
console.log(json.answer);
console.log("Done API Call");
至:
$.getJSON('https://script.google.com/macros/s/*encrpyted-URL*/exec?callback=?', function(json) {
console.log(json.answer);
console.log("Done API Call");
注意:
Prepare API Call
、End
、This is an answer
和Done API Call
的值。参考文献:
如果这不是你想要的结果,我很抱歉。
https://stackoverflow.com/questions/54370900
复制相似问题