Skip to content
조회 수 6671 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

구글 스프레드시트 ajax POST를 통한 기록 따라해보기

 

 

 

구글 스프레드시트를 데이터베이스로 이용하기 - 1. ajax POST를 통한 기록 편
을 읽고 한번 따라해 봤습니다.
 

 

 

1.  우선 시트1을 하나 만들고,

스프레드시트 ajax 기록-1.png

 

 

2. 메뉴의 도구 -> 스크립트 편집기를 선택합니다.

스프레드시트 ajax 기록-2.png

 

 

3. 빈프로젝트를 선택 -> 아래의 코드 입력 -> 디스켓모양 버튼을 눌러 스크립트를 저장 -> 실행-setup을 선택 -> 인증을 요청 -> 동의 -> 한번더 실행-setup을 선택  -> 게시-웹 앱으로 배포를 선택합니다.

 

* 파란색으로 표시한 시트1은 스프레드시트에서 ajax요청을 기록할 시트 이름입니다. 

//  1. Enter sheet name where data is to be written below

        var SHEET_NAME = "시트1";

         

//  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());

}

 

이제 위에서 복사해둔 웹 앱 URL을 통해 ajax GET/POST 요청을 보낼 수 있습니다.

ajax명령어를 사용하려면 skin.html에 jQuery스크립트를 포함해야합니다.

예)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

 

 

url은 복사해둔 웹앱 URL을 사용하면 됩니다.

 

다음은 ajax 예제입니다.

$.ajax({

  url: "웹앱URL",

  data: {A:"a", B:"b"},

  type: "POST"

});

중요 : (스프레드시트에는 미리 첫번째 행에 A가 기록된 열과 B가 기록된 열이 존재해야 a, b가 기록됩니다.)

 

 


 

 

 

스프레드시트 ajax 기록-3.png

 

위의 이미지에 나오는 게시할 수 있는 웹앱URL을 복사후 test.html 파일을 만들때 웹앱URL을 수정합니다.

 

<!DOCTYPE html>

<html lang="ko">

    <head>

        <meta charset="utf-8">

        <title>Ajax upload example</title>

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

 

<script type="text/javascript">

$.ajax({

  url: "웹앱URL",

  data: {A:"a", B:"f"},

  type: "POST"

});

 

</script>

 

 

테스트 해보면 잘 될 껍니다. 

근데 수정은 어떻게 하지?

 

 

5표 투표거부

API, GmailApp 및 MailApp 모두 고급 옵션을 통해 HTML 본문을 보낼 수 있습니다. 아래 코드를 사용하여 HTML 형식의 텍스트를 둘 다 보낼 수있었습니다.

암호

// global var 
var html =  
    '<body>' + 
      '<h2> Test </h2><br />' +
        '<p> Greetings Earthling </p>' +
    '</body>'    

function testGmailApp() {  
  GmailApp.sendEmail(
    'your@emailaddress.com',         // recipient
    'test GmailApp',                 // subject 
    'test', {                        // body
      htmlBody: html                 // advanced options
    }
  ); 
}

function testMailApp() {
  MailApp.sendEmail(
    'your@emailaddress.com',         // recipient
    'test MailApp',                  // subject 
    'test', {                        // body
      htmlBody: html                 // advanced options
    }
  ); 
}

 

 

#구글 #스프레드시트 #ajax #POST

로그인 후 댓글쓰기가 가능합니다.

?

  1. 구글 스프레드시트에서 셀값이 특정일에서 현재일과 3일 이내의 범위에 들어오면 이메일을 발송하는 방법

  2. Google Spreadsheet (Docs) 에서 우리은행 환율정보 이용하기

  3. 음력변환

  4. Google SpeadSheet 조건에 맞는 데이터만 참조하여 가져오기(importrange, Query)

  5. 구글캘린더 CSV 파일로 일괄 기록하기

  6. 구글 스프레드시트 설문지 내맘대로 수정하기

  7. 구글 스프레드시트를 이용한 지메일 예약발송 방법

  8. 스프레드시트 autohotkey html gmail 스마트폰 이용하여 핑로스 즉시 알림받기

  9. 구글 스프레드시트에서 O열=입금완료 가 있는 행은 행 전체가 노란색으로 변하게 하기

  10. 스프레드시트의 내용이 수정될 경우 즉시 메일발송하는 스크립트 테스트 중

  11. 구글 앱스 스크립트(Google Apps Script) 외부에서 실행하기

  12. google spreadsheets html form post로 전달받기

  13. 구글 앱스 스크립트(Google Apps Script) 외부에서 실행하기

  14. 구글 스프레드시트 ajax POST를 통한 기록 따라해보기

  15. [구글스프레드시트] 현재의 셀주소 참조(address, cell)

  16. 구글 드라이브에서 다른 파일 데이터 참조하기

  17. 구글 스프레드시트 쿼리 사용하기 #3 날짜편

  18. 스프레드시트 api append & update php 셀 내용 수정

  19. 구글 스프레드시트(Google Spreadsheet)를 데이터베이스로 활용하기

  20. 스프레드시트 스크립트 소스

Board Pagination Prev 1 2 Next
/ 2

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소