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
번호 분류 제목 날짜 조회 수
14 [Docs]스프레드시트 구글 스프레드시트를 이용한 지메일 예약발송 방법 file 2017.04.30 10788
13 [Docs]스프레드시트 구글 스프레드시트 설문지 내맘대로 수정하기 file 2016.08.13 11611
12 [Docs]스프레드시트 스프레드시트 api append & update php 셀 내용 수정 4 2016.08.08 5312
11 [Docs]스프레드시트 Google SpeadSheet 조건에 맞는 데이터만 참조하여 가져오기(importrange, Query) 1 file 2016.08.06 12919
10 [Docs]스프레드시트 구글 드라이브에서 다른 파일 데이터 참조하기 file 2016.08.06 6301
9 [Docs]스프레드시트 스프레드 웹게시로 불러오기 1 2016.06.24 4704
8 [Docs]스프레드시트 Google 문서도구를 컴퓨터에 동기화 2015.11.18 4377
7 [Docs]스프레드시트 구글 스프레드시트(Google Spreadsheet)를 데이터베이스로 활용하기 file 2015.07.20 5077
6 [Docs]스프레드시트 구글드라이브 API file 2015.07.09 4541
5 [Docs]스프레드시트 Extending Google Sheets 2015.02.10 4646
4 [Docs]스프레드시트 구글 스프레드시트(Google Spreadsheet)를 데이터베이스로 활용 2015.02.10 4521
3 [Docs]스프레드시트 쇼킹한 웹 긁어오기 2014.11.11 3903
2 [Docs]스프레드시트 음력변환 2014.11.11 17848
1 [Docs]스프레드시트 Google Spreadsheet (Docs) 에서 우리은행 환율정보 이용하기 2014.11.11 29859
Board Pagination Prev 1 2 Next
/ 2

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소