简体   繁体   中英

Accessing multiple parameter values in Google Apps Script

From this article from Martin Hawksey, summarized:

a script bound to the Sheet is published as a web app, a form uses jQuery's $.ajax to send the request to that web app, and the web app handles the parameters into columns of the Sheet with headers matching the names of each param. (the script in this article makes use of PublicLock, which I've changed to ScriptLock)

My problem revolves around checkboxes. Inside the request, I'll see

...fruit=apple&fruit=banana&fruit=cantaloupe...

and the Apps Script will see this as well, passing e to a function handleResponse() which is triggered from doPost(e) . To access the values for the parameters in the request, we use e.parameter or e.parameters . I've chosen the latter to accommodate for checkboxes and multiple values for that particular parameter.

What's not happening, though, is exactly that: only the first checkbox value is being sent through. To iterate through params, we use

for (i in headers) {
   if (headers[i] == "Timestamp") {
     row.push(new Date());
   } else {
      row.push( e.parameters[headers[i]] );
   }
}

to push the values for each parameter that matches a column header into a new array that will be entered as a new row. To do that, Hawksey uses

sheet.getRange(nextRow, 1, 1, row.length).setValues([row])

I guess I'm having trouble understanding what e.parameters does and how I can access the those values. I understand that the parameters property houses the values of each name as arrays , but I can't get an array's entire list of elements to be the value for a cell in a row. Can someone help me understand what e.parameters does, and how I can better get to all of the values I need?

e.parameters is an object where the parameters are the object keys and the values are stored in an array. So, a request like this:

url?fruit=apple&fruit=orange&fruit=lime&animal=giraffe

would yield an object like this:

{'fruit': ['apple', 'orange', 'lime'], 'animal': ['giraffe']}

If you have to put all values for fruit into one cell, you might try:

e.parameters.fruit.join(',')

which will return a string with each value separated by a comma. Then, if you need to separate the values again, you could use String.split() (docs here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM