由于参考错误,csv似乎没有出现

时间:2019-12-21 00:29:14

标签: javascript html json csv google-apps-script

我对这一切还是很陌生的,所以我很确定这只是我的简单疏忽,但我无法运行它。

当我部署下面的代码并单击按钮时,它不会执行任何操作。当我在浏览器中检查html时,它说“ userCodeAppPanel:1未捕获的ReferenceError:csvHTML未定义     在HTMLInputElement.onclick“

当我从Code.gs运行功能csvHTML时,我可以在Logger.log中看到预期的结果,因此问题似乎不在于我的code.gs

我想要实现的是在html中显示csv结果。如果一切正常,我将希望以其他方式使用数据。

下面是我的代码。

Index.html:

<!DOCTYPE html>
<!-- styles -->
<?!= HtmlService.createHtmlOutputFromFile("styles.css").getContent(); ?>

<div class="content">

  <h1>csv representation</h1>

  <input class="button" type="submit" onclick="html();" value="Refresh" id="refresh"><br>
  <div id="tabel"></div>
  <svg class="chart"></svg>

</div>

<!-- javascript -->
<script src="//d3js.org/d3.v3.min.js"></script>
<?!= HtmlService.createHtmlOutputFromFile("chart.js").getContent() ?>
<?!= HtmlService.createHtmlOutputFromFile("main.js").getContent() ?>

<script>

function html()
{
var aContainer = document.createElement('div');
    aContainer.classList.add('loader_div');
    aContainer.setAttribute('id', 'second');
    aContainer.innerHTML = "<div class='loader_mesage'><center>Fetching csv list. Please be patient!<br /> <br /><img src='https://i.ibb.co/yy23DT3/Dual-Ring-1s-200px.gif' height='50px' align='center'></img></center></div>";
    document.body.appendChild(aContainer);

google.script.run
           .withSuccessHandler(showTable)
           .csvHTML();
}

function showTable(tabel)
{
document.getElementById("tabel").innerHTML = tabel;
var element = document.getElementById("second");
element.parentNode.removeChild(element);
}
</script>

和Code.gs:

function doGet(e) {
  return HtmlService.createTemplateFromFile("index.html")
    .evaluate()
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}


// Fecth Data and make a csv output.

function csvHTML()
{
var query = "{ 'query': 'SELECT * FROM `<some table>` limit 1000;', 'useLegacySql': false }";
var job = BigQuery.Jobs.query(query, <projectName>);
var json = JSON.parse(job);
var tabel = json2csv(json); 
Logger.log(tabel)
return tabel;  
}

function json2csv(json, classes) {
  var headerRow = '';
  var bodyRows = '';
  classes = classes || '';

  json.schema.fields.forEach(function(col){
    headerRow +=col.name+",";
  })

  json.rows.forEach(function(row){
   row.f.forEach(function(cell){
      bodyRows +=cell.v+",";
    })

                  })
     return headerRow + bodyRows }

2 个答案:

答案 0 :(得分:1)

因此,感谢TheMaster的建议,我将其重写为以下内容:

index.html:

<!-- javascript -->
<script src="//d3js.org/d3.v3.min.js"></script>

<script>

function html()
{
var aContainer = document.createElement('div');
    aContainer.classList.add('loader_div');
    aContainer.setAttribute('id', 'second');
    aContainer.innerHTML = "<div class='loader_mesage'><center>Fetching csv list. Please be patient!<br /> <br /><img src='https://i.ibb.co/yy23DT3/Dual-Ring-1s-200px.gif' height='50px' align='center'></img></center></div>";
    document.body.appendChild(aContainer);


google.script.run
           .withSuccessHandler(showTable)
           .csvHTML();
}

function showTable(tabel)
{
document.getElementById("tabel").innerHTML = tabel;
var element = document.getElementById("second");
element.parentNode.removeChild(element);
}
</script>

<!DOCTYPE html>


<div class="content">

  <h1>csv representation</h1>

  <input class="button" type="submit" onclick="html();" value="Refresh" id="refresh"><br>
  <div id="tabel"></div>
  <svg class="chart"></svg>

</div>

Code.gs尚未修改。

似乎<?!= htmlService.createHtmlOutputFromFile("styles.css").getContent(); ?>和其他createHtmlOutputFromFile正在妨碍您。最终,我需要这些,但是我将在以后的阶段中弄清楚如何将其合并。

感谢所有的建议和帮助!

答案 1 :(得分:0)

免责声明:我对Google Apps脚本的使用经验为零,因此请耐心等待。

看着他们的documentation for BigQuery,看来您没有正确查询数据库。您对Logger.log()显示正确的输出感到惊讶。看来它不应该工作。

如果我对,我建议您将Code.gs文件更改为:

function doGet(e) {
  return HtmlService.createTemplateFromFile("index.html")
    .evaluate()
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}


// Fetch Data and make a csv output.

function csvHTML() {
  var results = runQuery('SELECT * FROM `<some table>` limit 1000;');
  var tabel = toCSV(results);
  Logger.log(tabel);
  return tabel;
}

/**
 * Runs a BigQuery query and logs the results in a spreadsheet.
 */
function runQuery(sql) {
  // Replace this value with the project ID listed in the Google
  // Cloud Platform project.
  var projectId = 'XXXXXXXX';

  var request = {
    query: sql,
    useLegacySQL: false
  };
  var queryResults = BigQuery.Jobs.query(request, projectId);
  var jobId = queryResults.jobReference.jobId;

  // Check on status of the Query Job.
  var sleepTimeMs = 500;
  while (!queryResults.jobComplete) {
    Utilities.sleep(sleepTimeMs);
    sleepTimeMs *= 2;
    queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId);
  }

  // Get all the rows of results.
  var rows = queryResults.rows;
  while (queryResults.pageToken) {
    queryResults = BigQuery.Jobs.getQueryResults(projectId, jobId, {
      pageToken: queryResults.pageToken
    });
    rows = rows.concat(queryResults.rows);
  }
  var fields = queryResults.schema.fields.map(function(field) {
    return field.name;
  });
  var data = [];
  if (rows) {
    data = new Array(rows.length);
    for (var i = 0; i < rows.length; i++) {
      var cols = rows[i].f;
      data[i] = new Array(cols.length);
      for (var j = 0; j < cols.length; j++) {
        data[i][j] = cols[j].v;
      }
    }
  }
  return {
    fields: fields,
    rows: rows
  };
}

function toCSV(results) {
  var headerRow = results.fields.join(',');
  var bodyRows = results.rows.map(function(rowData) {
      return rowData.map(function(value) {
        // for proper CSV format, if the value contains a ", 
        // we need to escape it and surround it with double quotes.
        if (typeof value === 'string' && value.indexOf('"') > -1) {
          return '"' + value.replace(/"/g, '\\"') + '"';
        }
        return value;
      });
    })
    .join('\n'); // join the lines together with newline characters
  return headerRow + '\n' + bodyRows;
}

提醒:我还没有测试过,我纯粹是基于我对Javascript及其文档和示例代码的了解来编写此代码。