简体   繁体   中英

REST API Google Sheets - use from client JS

Is there any way how to use google sheets for write and read data directly from client javascript in a web browser?

Data security is no issue here. I just need some small free database for single page web application without web server.

Yes, there is a way. Sometimes i use google sheet to save form data. So i wont give you full solution, but it could be good starting point.

  • Create or open a spreadsheet in Google Sheets.
  • Select the menu item Tools > Script editor. If you are presented with a welcome screen, click Blank Project on the left to start a new project.
  • Delete any code in the script editor. And simply copy and paste the code into the script editor:

 // 1. Enter sheet name where data is to be written below var SHEET_NAME = "Sheet1"; // 2. Run > setup // // 3. Publish > Deploy as web app // - enter Project Version name and click 'Save New Version' // - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously) // // 4. Copy the 'Current web app URL' and post this in your form/script action // // 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case) var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service // If you don't want to expose either GET or POST methods you can comment out the appropriate function function doGet(e){ return handleResponse(e); } function doPost(e){ return handleResponse(e); } function handleResponse(e) { // shortly after my original solution Google announced the LockService[1] // this prevents concurrent access overwritting data // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html // we want a public lock, one that locks for all invocations var lock = LockService.getPublicLock(); lock.waitLock(30000); // wait 30 seconds before conceding defeat. try { // next set where we write the data - you could write to multiple/alternate destinations var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key")); var sheet = doc.getSheetByName(SHEET_NAME); // we'll assume header is in row 1 but you can override with header_row in GET/POST data var headRow = e.parameter.header_row || 1; var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var nextRow = sheet.getLastRow()+1; // get next row var row = []; // loop through the header columns for (i in headers){ if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column row.push(new Date()); } else { // else use header name to get data row.push(e.parameter[headers[i]]); } } // more efficient to set values as [][] array than individually sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // return json success results return ContentService .createTextOutput(JSON.stringify({"result":"success", "row": nextRow})) .setMimeType(ContentService.MimeType.JSON); } catch(e){ // if error return this return ContentService .createTextOutput(JSON.stringify({"result":"error", "error": e})) .setMimeType(ContentService.MimeType.JSON); } finally { //release lock lock.releaseLock(); } } function setup() { var doc = SpreadsheetApp.getActiveSpreadsheet(); SCRIPT_PROP.setProperty("key", doc.getId()); } 

  • Publish > Deploy as web app.
  • Choose your security options. And press "Deploy"
  • Now URL will be generated for you, in my case this URL is: https://script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exe
  • Before using your link don't forget to Run > Setup.
  • Finaly you can send data to your sheet by post'ing form data to your URL. And first line of your sheet should contain names of fields what your are planing to save. In this case write in A1: Name, in B1: Mail and in C1-> Comment.

  <form id="form" action="YOUR_URL"> <label>Name</label><br /> <input name="Name" type="text" value="" /><br /> <label>Email</label><br /> <input name="Email" type="text" value="" /><br /> <label>Comment</label><br /> <textarea name="Comment" /><br /> <input type="submit" value="Send" /> </form> 

Now you can send data with javascript to your URL. If you look closely at the url, you will be able to find the spreadsheet's key. My document key is: 10vmpPMTBqsXYsTH20a_kU-GTJ06KYxXWg-E2aAtm_dM

The JSON feeds for any Google Spreadsheet is available at:

JSON Format: https://spreadsheets.google.com/feeds/list/YOUR_KEY/od6/public/basic?alt=json

And of cause your document should be published before accessing JSON URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM