javascript 如何使用sessionStorage与JS和谷歌应用程序脚本?

0vvn1miw  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(167)

如果sessionStorage中没有可用的数据,我会尽量避免调用服务器端函数getSuppliersForPoFromSS(orderPo, origin),但我不确定是否得到了正确的结构:

**/
 * Gets determined supplier from Spreadsheet and builds a select input with options.
 * @param {Object} selecObject
 * @param {String} origin specifying where this is going to be obtained from
 */
function loadSuppliersForPoFromSS(selectObject, origin) {
  orderPo = selectObject.value;
  document.getElementById('selectSupplier').innerHTML = '';
   
  //My shot at it, trying to a 2D array. e.g.: [["Item1", "Item2"]]
  let ar = JSON.parse(sessionStorage.getItem(orderPo));
 
   
  if(!ar){   
  google.script.run.withSuccessHandler(function(ar) {
    let select = document.getElementById('selectSupplier');
    let options = select.getElementsByTagName('option');
    for (let i = options.length; i--;) {
      select.removeChild(options[i]);
    }
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    select.appendChild(option);
    ar.forEach(function(item, index) {
      let option = document.createElement("option");
      option.value = item.toLowerCase();
      option.text = item;
      select.appendChild(option)
    });
  }).getSuppliersForPoFromSS(orderPo, origin);
 } else {
  //Do I rewrit the part that builds the options with data from sessionStorage?
}
46scxncf

46scxncf1#

由于google.script.run是异步的,这意味着它后面的命令不会等待google.script.run完成并返回,您可以创建一个内部函数getAr(),它将作为google.script.run的成功处理程序的一部分被调用,或者在sessionStorage返回值时被单独调用。

function loadSuppliersForPoFromSS(selectObject, origin) {
  orderPo = selectObject.value;
  document.getElementById('selectSupplier').innerHTML = '';
  
  function getAr(ar) {
    let select = document.getElementById('selectSupplier');
    let options = select.getElementsByTagName('option');
    for (let i = options.length; i--;) {
      select.removeChild(options[i]);
    }
    let option = document.createElement("option");
    option.value = "";
    option.text = "";
    select.appendChild(option);
    ar.forEach(function(item, index) {
      let option = document.createElement("option");
      option.value = item.toLowerCase();
      option.text = item;
      select.appendChild(option)
    });
  }

  //My shot at it, trying to a 2D array. e.g.: [["Item1", "Item2"]]
  let ar = JSON.parse(sessionStorage.getItem(orderPo));
   
  if(!ar){   
    google.script.run.withSuccessHandler(function(ar) {
      getAr(ar);
    }).getSuppliersForPoFromSS(orderPo, origin);
  } 
  else {
    getAr(ar);
  }
}

相关问题