簡體   English   中英

使用Google Apps腳本將數組傳遞給客戶端功能?

[英]Passing an array to client side function using Google apps script?

的HTML

<html>
<table>

 <tr>
  <select id="Ultra"  onchange="getForm()">
          <option value="0.0">1</option>
          <option value="1.0">2</option>
          <option value="2.0">3</option>
          <option value="3.0">4</option>
      </select>
   </tr>
<tr>

<td id="demo">
 <script>

function getForm()
            {
         google.script.run.withSuccessHandler(myFunction).myFuncti();
         }
        function myFunction(arry) 
        { 
           var x = document.getElementById("Ultra").value;
           for(i=0;i<arry.length;++i)
           {
             if(arry[i][0] == x)
             {
              var a = arry[i][1];
              }
              document.getElementById("demo").innerHTML = a;

             }

       }


   </script>
   </td>
   </tr>

</table>
</html>

我使用select創建了一個下拉菜單,之后我調用了客戶端函數getForm() 在該函數中,我使用google.script.run類調用服務器端函數myFuncti() ,這將返回一個數組,該數組將作為參數傳遞給客戶端函數myfunction()

如果使用Logger.log() ,則服務器端函數將成功返回數組值!

這是一個2D數組..我是否以正確的方式將其傳遞給myFunction()

如果您無法解決問題,請添加評論,我會回復

這是代碼的外觀,請注意使用console.log()在客戶端進行調試(CTRL-SHFT-I通常在瀏覽器中打開開發人員控制台窗口):

index.html

<div>
  <select id="Ultra" onchange="getForm()">
    <option value="1.0">1</option>
    <option value="2.0">2</option>
    <option value="3.0">3</option>
    <option value="4.0">4</option>
  </select>
  <p id="demo"></p>
</div>

<script>

function getForm() {

  google.script.run.withSuccessHandler(myFunction).myFuncti();
}

function myFunction(arry) {

  var x = document.getElementById("Ultra").value;
  var y = parseInt(x, 10);
  var i = 0;
  var a;

  console.log('x (string) = ' + x);
  console.log('y (number) = ' + y);  
  console.log(arry);

  for (; i < arry.length; i++) {

    a = arry[i];

    console.log('a = ' + a);

    if (a === y) {

      console.log('a === y');
      document.getElementById("demo").innerHTML = a;
    }
  }
}

</script>

代碼

function doGet(form) {

  return HtmlService
    .createHtmlOutputFromFile('index');
}

function myFuncti() {

  return [1, 2, 3, 4];
}

這是一個有效的演示以及腳本

根據文檔,您可以簡單地從服務器端函數返回數組,並直接在客戶端Javascript中使用。

相關文檔: https : //developers.google.com/apps-script/guides/html/communication#parameters_and_return_values

使用瀏覽器的開發人員工具調試客戶端Javascript。

一些猜測:

您的問題可能與您在客戶端訪問數組的方式有關,也許if(arry[i][0] == x)永遠不匹配,或者您對索引1而不是0的引用在線上不正確var a = arry[i][1];

另外,您在if的花括號內聲明變量“ a”,然后在這些花括號外分配變量,也許您的意思是:

for(i=0;i<arry.length;++i) 
{
   if(arry[i][0] == x)   
   {
      var a = arry[i][1];
     document.getElementById("demo").innerHTML = a;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM