首页 > 解决方案 > 通过 AppScript 将 Facebook 广告帐户数据放入下拉选项列表

问题描述

我已经通过这个函数 makeRequest 成功检索了 Ad Accounts 数据。我可以在 appsscript 执行日志中看到结果 -

console.log(data.adaccounts.data[0].account_id); //26123718

我已经将数据存储在这里

常量数据 = JSON.parse(响应);

如何将广告帐户 ID 提取到下拉列表中,如 HTML 中所示

<select id="select">
   
</select>
    function makeRequest() {
      
      // get the Facebook Service
      const facebookService = getFacebookService();
      
      // get the access token
      const access_token = facebookService.getAccessToken();
      console.log(access_token);
      
    
      //set up the API Endpoint
    
      const base = 'https://graph.facebook.com/v10.0/';
      
      const endpoint = 'me?&fields=adaccounts';
    
      const url = base + endpoint;
      console.log(url);
    
      const params = {
    
        headers: {
    
          Authorization: 'Bearer ' + access_token
        }
        
      }
      
      const response = UrlFetchApp.fetch(url,params);
      console.log(response);
    
      const data = JSON.parse(response);
      console.log(data);
    
      console.log(data.adaccounts.data[0].account_id);
    
       
}


 
 

标签: google-apps-script

解决方案


在您的 html 文件中,您可以使用google.script.run.withSuccessHandler()调用 Code.gs 中的函数,如果该函数成功返回,它会将数据传递给回调函数。

例子:

代码.gs

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate();
}
 
//GET DATA FROM GOOGLE SHEET AND RETURN AS AN ARRAY
function makeRequest(){
  //Insert your function that will fetch data from facebook ads here

  //For example the account IDs are "12345","32456", "23423" 
  var account_id = ["12345","32456", "23423"];
  return account_id;
}
 
//INCLUDE JAVASCRIPT AND CSS FILES
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

索引.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top"> 
    <?!= include('JavaScript'); ?>
  </head>
  <body>
    <div class="container">
      <br>
      <select id="select">
      </select>
    </div>  
  </body>
</html>

JavaScript.html

<script>
  // This will call makeRequest() function in the Code.gs and 
  // pass the data to appendToDropDown function 
  google.script.run.withSuccessHandler(appendToDropDown).makeRequest();
 
  //This function will add option to select tag 
  function appendToDropDown(ids){
    var select = document.getElementById('select');
    for (var i=0; i<ids.length; i++) {      
      var opt = document.createElement('option');     
      opt.text = ids[i]
      select.add(opt);
    }
  }
</script>

输出:

在此处输入图像描述

参考:


推荐阅读