Skip to content
조회 수 6662 추천 수 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

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

?

List of Articles
번호 분류 제목 날짜 조회 수
2344 종교와철학 "박근혜 '애' 낳는 그림 그린 홍씨, 누군가 자신의 어머니를 저런식으로 그렸다면? file 2012.11.19 6344
2343 AutoHotKey #ifwinactive & #ifwinexist 윈도우창 마다 핫키의 용도를 다르게 사용하는 방법 2011.02.14 16518
2342 만들기 <!--f644fe64217d47f8abef1fe9b7150c48--> secret 2010.10.29 3929
2341 Excel 'C:Documents.xlsx' 을(를) 찾을 수 없습니다. 라는 오류 메시지가 나오는 경우 대처방법 2015.01.28 4765
2340 유용한상식 '작업의 정석' 과외받는 남자들 12 2013.03.04 7133
2339 WindowsTip (nPDF) 프린터 인쇄 내용을 PDF 파일로 변환하기 2015.01.24 2271
2338 재미재미 (쇼킹한 음료광고)Thailand funny slimming greentea commercial 1 2 2012.08.25 5530
2337 일상 (펌)개성공단에서 4월 13일 나온 근무자입니다 2013.04.17 20444
2336 유용한상식 (해외송금)SWIFT 국민은행 송금 및 은행별 SWIFT CODE LIST 2014.02.03 17062
2335 재미재미 * 바람피운 남편을 어떻게...* 2010.12.19 5309
Board Pagination Prev 1 2 3 4 5 ... 235 Next
/ 235

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소