function fetch() {
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
// This variable ONLY exists inside of the fetch function.
// once this function exits, it is gone.
var urlResponse = UrlFetchApp.fetch(url, options);
}
function logResponse(){
// Nope, this is an entirely SEPARATE variable with the same name.
Logger.log(urlResponse); //This must return the data from the urlResponse variable
}
解決方案:要麼一)在價值傳遞給logResponse()或將var UrlResponse
移動到兩個功能可用的外部範圍。但是,請保留分配。
選項1
var urlResponse;
function fetch() {
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
// This variable ONLY exists inside of the fetch function.
urlResponse = UrlFetchApp.fetch(url, options);
}
function logResponse(){
// Nope, this is an entirely SEPARATE variable with the same name.
Logger.log(urlResponse); //This must return the data from the urlResponse variable
}
選項2
function fetch() {
var endpoint = 'login';
var url = 'https://example.com/api/'+endpoint;
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
// This variable ONLY exists inside of the fetch function.
var urlResponse = UrlFetchApp.fetch(url, options);
logResponse(urlResponse);
}
function logResponse(urlResponse){
Logger.log(urlResponse); //This must return the data from the urlResponse variable
}
範圍:在'function setVar()'之前聲明'a'如果你不這樣做,每個'a'封裝在每個功能,就像有兩個不同的'a' –