如何针对 Google Apps Script ContentService 发出 XHR/ajax 请求? [英] How do I make XHR/ajax requests against Google Apps Script ContentService work?

查看:32
本文介绍了如何针对 Google Apps Script ContentService 发出 XHR/ajax 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Google Apps Script ContentService,它发出一个字符串,如Hello world Sat Jul 14 2012 14:17:21 GMT+1000 (EST)",网址是 https://script.google.com/macros/s/AKfycbxbFFG95mi8X3PWcxpXanyc7p7p3OWbclXch_bbWczQ/exec 和 open随意打它.代码是:

I have a simple Google Apps Script ContentService that emits a string like "Hello world Sat Jul 14 2012 14:17:21 GMT+1000 (EST)" The url is https://script.google.com/macros/s/AKfycbxbFFG95mi8PWVNCE8366XaxnXQrt6p7p3OWbclXch_bbWczQ/exec and it's open to anonymous. Feel free to hit it. The code is:

function doGet() {
  var output = ContentService.createTextOutput()
      .setMimeType(ContentService.MimeType.TEXT)
      .setContent("Hello world " + new Date());
  Logger.log(output.getContent());
  return output;
}

当我在浏览器中访问 URL 时,它会按预期返回字符串 (pass.png).当我在 XHR(ajax 调用)中使用相同的 URL 时,它失败并显示空错误.在 Chrome 的开发人员工具中,重定向是 "(canceled)" (fail.png) .这是重现失败的代码:

When I visit the URL in a browser it returns the string as expected (pass.png). When I use the same URL in an XHR (ajax call) it fails with an empty error. In the developer tools in Chrome the redirect is "(canceled)" (fail.png) . Here is the code to reproduce the fail:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
  xhr=new XMLHttpRequest();
  xhr.onreadystatechange=function() {
  if (xhr.readyState==4 && xhr.status==200) {
    document.getElementById("myDiv").innerHTML=xhr.responseText;
    }
  };
  xhr.open("GET","https://script.google.com/macros/s/AKfycbxbFFG95mi8PWVNCE8366XaxnXQrt6p7p3OWbclXch_bbWczQ/exec",true);
  xhr.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get Content via XHR</button>
</body>
</html>

直接请求:XHR 请求:我的问题(希望足够具体):如何从 example.com 上的普通旧网页进行 XHR 调用,以从匿名 Google Apps Script ContentService 脚本中获取内容?

Direct request: XHR request: My question (hopefully specific enough): How do I make XHR calls from a plain old web page on example.com to GET content from anonymous Google Apps Script ContentService scripts?

推荐答案

我不确定目前是否可行.我们考虑了 JSONP 方法(它确实有效;我已经测试过了),但我认为没有测试过针对 ContentService 制作 XHR 的情况.我们可能需要为此设置 CORS 标头.请在问题跟踪器上提交功能请求,我们会看看是否可以完成.

I am not sure this is currently possible. We considered the JSONP method (which does work; I've tested it) but I don't think making an XHR against ContentService was ever tested. We'd probably need to set up CORS headers for this. Please file a feature request on the issue tracker and we'll see if it can be done.

这篇关于如何针对 Google Apps Script ContentService 发出 XHR/ajax 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆