[英]ReferenceError: XMLHttpRequest is not defined Google apps script
[英]Access parameters in a XMLHttpRequest Google Apps Script
我目前正在尝试使用Google Apps脚本访问POST请求的参数。 我可以使用e.parameter记录params对象,尽管我似乎无法通过使用e.parameter.name访问对象的键。
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps脚本
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
有一些细微的怪癖,它们通过http构成数据的方式不同。 例如,我注意到当json数据的通常标头为Content-Type:application / json时,您正在使用Content-type“ application / x-www-form-urlencoded”。
我添加了一行,仅返回e变量的内容,因此您可以看到返回的内容。
我使用curl使用以下命令对其进行调试。
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
我收到的回复是:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
您可以看到,就我而言,json是在content字段而不是参数中返回的。
您可以使用脚本尝试此操作,以查看得到的结果。 您也可以尝试更改Content-Type。
经过进一步测试后,我认为您最好以表单数据而不是json的形式提交字段。 通过将您的JavaScript修改为:,我已经可以恢复参数。
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.