0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【GAS】doPost内でcheckboxの送信内容を配列で受け取りたい

Last updated at Posted at 2022-05-24

はじめに

GoogleFormではなく別途htmlのフォームを作ってGASでそのPOSTされた内容を受け取りたい場合、チェックボックスのように同じ名前で複数送られる形式のものは、e.parameter内では1つしか受け取ることができませんでした。
なので、別途送られた内容を分解してセットしてあげるようにします。

内容

今回はこの記事を参考にしました。
JavaScriptでクエリストリングを取得&分解&整形する方法
e.postData.contentsに必要なデータが入っているので、それを分解します。

//======================================================================================================
// リクエストパラメータを分解して利用可能な形に整形する
//======================================================================================================
function getParameters(e){

  var params = {};

  //KeyValue単位で分割する
  //デコード前に+を半角スペースに変換しておく
  var postItems = e.postData.contents.replace(/\+/g," ").split('&');
  var reg = /^(\w+)\[(\w*)\]$/;

  postItems.forEach(function(postItem){

    if(postItem.length > 0){

      //KeyとValueに分けてからデコードする
      var item = postItem.split('=');
      var key = decodeURIComponent(item[0]);
      var value = item[1] ? decodeURIComponent(item[1]) : "";

      //配列か変数かチェック
      var matches = reg.exec(key);

      //変数(例:<input name="id" value="xxx">)
      if (!matches) {
        params[key] = value;

      //配列(例:<input name="id[]" value="xxx">)
      }else if(!matches[2].length){
        key = matches[1];
        if(!(key in params)){
          params[key] = [];
        }
        params[key].push(value);

      //連想配列(例:<input name="id[test1]" value="xxx">)
      }else{
        key = matches[1];
        if(!(key in params)){
          params[key] = {};
        }
        params[key][matches[2]] = value;      
      }    
    }
  });
  return params;
}

getParametersにdoPost(e)で取得したeを渡すと、例えば

<input type="checkbox" name="id[]" value=1>
<input type="checkbox" name="id[]" value=3>
<input type="checkbox" name="id[]" value=5>

のような形のデータは、配列になって格納され、

<input type="checkbox" name="user[name_1]" value=1>
<input type="checkbox" name="user[name_2]" value=3>
<input type="checkbox" name="user[name_3]" value=5>

のような形のデータは連想配列になって格納されます。
正規表現内で連想配列のキーに指定できる文字は\wで指定しているので、キーは英数字とアンダースコアで指定してください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?