如何将Google App脚本结果返回到外部网页?

时间:2019-06-11 16:19:09

标签: javascript html google-apps-script

我找到了一个GAS,该GAS会在列中搜索通过HTML表单输入到Google表格中的ID号。找到ID#后,它将在不同的列中检查日期,并根据相对于当前日期的列中的日期返回一条消息。当我运行GAS时,我从脚本的结果中得到了返回的消息,但是我要做的是将脚本的结果返回到Web表单中,以在用户提交表单后通知用户该消息。它不必是GAS……如果有人可以用Java脚本做同样的事情,我是耳熟能详的。提前致谢。

我已经试图找出如何从html页面调用GAS的方法,但是没有成功。

GAS:

<!-- Search Sheet for Bottle Expiration date -->

var ss = SpreadsheetApp.openByUrl("GSURL");
var sheet = ss.getSheetByName("Entries");

function doGet(e){
 return search(e) ;
}  

function doPost(e){
 return search(e) ;
}  


function search(e){
 var id = e.parameter.last_name;

  var values = sheet.getRange(2, 2, sheet.getLastRow(),sheet.getLastColumn()).getValues();

  for(var i = 0;i<values.length; i++){

    if(values[i][0] == id ){
      i=i+2;

      var name = sheet.getRange(i,4).getValue();
      var hydroDate = Date.now()+14;
      var hydroalert = ContentService.createTextOutput("Bottle is due for Hydro").setMimeType(ContentService.MimeType.TEXT)
      if (hydroDate <= name)
      return hydroalert;
    }
  }
  return ContentService.createTextOutput("Id not found").setMimeType(ContentService.MimeType.TEXT);

}

HTML页面

<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>UFD Tour 2 Monthlies</title>

<!-- <link rel="stylesheet" type="text/css" href="style.css" media="screen, handheld"/> -->


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="ufd_tour_2_monthlies.js?rev=<?php echo time();?>"></script>
  <script type="text/javascript" src="qrscan.js?rev=<?php echo time();?>"></script>
<script src="https://rawgit.com/sitepoint-editors/jsqrcode/master/src/qr_packed.js">
</script>

  <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<!-- Place this within the <head> tag or just before the end of your <body> tag. -->
<script src="https://awesome-table.com/AwesomeTableInclude.js"></script>
</head>


<style> 
h2 {
   text-align: center;
  }
input[type=text], input[type=password] { 
    width: 100%; 
    padding: 12px 20px; 
    margin: 8px 0; 
    display: inline-block; 
    border: 1px solid #ccc; 
    box-sizing: border-box; 
} 
button { 
    background-color: #4CAF50; 
    color: white; 
    padding: 14px 20px; 
    margin: 8px 0; 
    border: none; 
    cursor: pointer; 
    width: 100%; 
} 
.cancelbtn { 
    padding: 14px 20px; 
    background-color: #f44336; 
} 
.cancelbtn,.signupbtn { 
    float: left; 
    width: 50%; 
} 

.container { 
    padding: 16px; 
} 


.clearfix::after { 
    content: ""; 
    clear: both; 
    display: table; 
} 


@media screen and (max-width: 300px) { 
    .cancelbtn, .signupbtn { 
    width: 100%; 
    } 
} 
  .form_container { width: 90%; max-width:450px; margin:20px 30px 40px 30px; padding:15px 20px; font-size:15px; line-height:25px; text-align:left; background:#EBEBEB; }
.form_field { display:block; width:100%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.form_button { display:block; width:100%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.form_message { }

  body, input {font-size:14pt}
input, label {vertical-align:middle}
.qrcode-text { display:block; width:90%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.qrcode-text-btn { display:block; text-align:center; width:90%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.qrcode-text-btn > input[type=file] {position:absolute; overflow:hidden; width:1px; height:1px; opacity:0}
</style> 
<body> 

<h2>Tour 2 Monthlies</h2> 


<div class="container"> 
     <form id="sheets" name="sheets" class="form_body">
       <label for="first_name">Date</label>
<input id="first_name" name="first_name" type="date" class="form_field" value="" placeholder="Select Date"/>
       <label for="last_name">Bottle Number</label>
<input id="last_name" name="last_name" class="form_field" onfocus="this.value='';" value="" placeholder="Select here to scan or enter manually"/>
       <input type="button" name="btnScanBarcode" id="btnScanBarcode" class="form_button" value="Scan Bottle" onclick="javascript:openQRCamera(this);"></button>

 <!-- <input id="last_name" name="last_name" type=text placeholder="Select here to scan or enter manually" class="qrcode-text"><label class="qrcode-text-btn"><input type=file accept="image/*" capture=environment onclick="openQRCamera(this);" tabindex=-1>Scan Bottle</label> 

  <script>function openQRCamera(node) {
  var reader = new FileReader();
  reader.onload = function() {
    node.value = "";
    qrcode.callback = function(res) {
      if(res instanceof Error) {
        alert("No QR code found. Please make sure the QR code is within the camera's frame and try again.");
      } else {
        node.parentNode.previousElementSibling.value = res;
      }
    };
    qrcode.decode(reader.result);
  };
  reader.readAsDataURL(node.files[0]);
}</script> -->

  <script>
function startBarcodeScanner() 
{    

    window.location.href = 'bwstw://startscanner?field=last_name';
}

</script>
       <label for="email">Bottle Location</label>
<select id="email" name="email" class="form_field" value="" placeholder="Bottle Location"/>
  <option>ENGINE 1</option>
<option>ENGINE 2</option>
<option>ENGINE 3</option>
<option>SQUAD 4</option>
<option>SQUAD 41</option>
<option>LADDER 1</option>
<option>TRUCK 1</option>
<option>TRUCK 2</option>
<option>TRUCK 3</option>
<option>ENGINE 5</option>
<option>ENGINE 6</option>
<option>ENGINE 7</option>
<option>RESCUE 1</option>
<option>RESCUE 2</option>
<option>RESCUE 3</option>
<option>STATION 1 SPARE</option>
<option>STATION 2 SPARE</option>
<option>STATION 3 SPARE</option>
<option>SPECIAL OPS</option>
<option>BC</option>
<option>COD</option>
<option>DC</option>
<option>EMSC</option>
<option>FINV</option>
<option>COMM</option>
<option>TRAIN</option>
<option>BOAT</option>
<option>SPARE MASK</option>
<option>O/S</option>
<option>OTHER LOCATION</option>
<option>OTHER VEHICLE</option>
  </select>


<input id="gs_code" name="gs_code" type="hidden" class="" value="=VLOOKUP(B:B,HydroBottles,4,FALSE)" placeholder=""/>
    <div class="clearfix"> 

     <input id="submit" name="submit" type="button" class="form_button" value="Enter Bottle" onClick="submit_form(); document.getElementById('last_name').value = ''; playAudio()"/>
         <audio id="beep">
  <source src="bleep.mp3" type="audio/mpeg">
</audio>

<div class="form_message" id="message">

  <script>
    var gs_hydrosearch = 'https://script.google.com/macros/s/AKfycby0VsXuYk-dODBhKpL-zFUeb5xI79Y8jGR0e20I/exec?id=gs_field';
    var gs_field = ['last_name'];
    function HydroSearch() {
    doPost(


  </script>




      </div>
    </div> 
</div> 

  <!-- Place this tag where you want the Awesome Table Widget to render -->
<div data-type="AwesomeTableView" data-viewID="-LfNI2wu42vUdIl5oy9c"></div>


</form> 
</body> 
</html> 

JS文件,用于将表单中的数据发送到Google Spreadsheet:

function submit_form() {    
    // Check Fields
    var complete = true;
    var error_color = '#FFD9D9';
    var fields = ['first_name','last_name','email','gs_code'];
    var row = '';
    var i;
    for(i=0; i < fields.length; ++i) {
        var field = fields[i];
        $('#'+field).css('backgroundColor', 'inherit');
        var value = $('#'+field).val();       
        // Validate Field
        if(!value) {
            if(field != 'message') {
                $('#'+field).css('backgroundColor', error_color);
                var complete = false;
            }
            } else {            
            // Sheet Data
            row += '"'+value+'",';
        }
    }

    // Submission
    if(complete) {      
        // Clean Row
        row = row.slice(0, -1);     
        // Config
        var gs_sid = 'GSID'; // Enter your Google Sheet ID here
        var gs_clid = 'Client ID'; // Enter your API Client ID here
        var gs_clis = 'API Client Secret'; // Enter your API Client Secret here
        var gs_rtok = '0Auth RT'; // Enter your OAuth Refresh Token here
        var gs_atok = false;
        var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Entries!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
        var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';  


         // HTTP Request Token Refresh
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {            
            var response = JSON.parse(xhr.responseText);
            var gs_atok = response.access_token;            
            // HTTP Request Append Data
            if(gs_atok) {
                var xxhr = new XMLHttpRequest();
                xxhr.open('POST', gs_url);
                xxhr.setRequestHeader('Content-length', gs_body.length);
                xxhr.setRequestHeader('Content-type', 'application/json');
                xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
                xxhr.onload = function() {
                    if(xxhr.status == 200) {
                        // Success
                              $('audio#beep')[0].play();
                        $('#message').hide().html("Bottle has been Entered! Scan next Bottle.").fadeIn().delay('1000').fadeOut().delay('7000');

                        } 

                               else {
                        // Fail
                        $('#message').html('<p>Row Not Added</p><p>Response:<br/>'+xxhr.responseText+'</p>');
                    }
                };
                xxhr.send(gs_body);
            }            
        };
        xhr.send();



    }


}

1 个答案:

答案 0 :(得分:0)

您的问题的答案封装在此documentation中,称为客户端到服务器通信。目前,您的问题范围很广,您需要做更多的研究,也许还需要进行一些调试。我还建议您借此机会参加[游览]并学习如何[询问]和[mcve]。