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
번호 분류 제목 날짜 조회 수
597 [Docs]스프레드시트 쇼킹한 웹 긁어오기 2014.11.11 3903
596 [Docs]스프레드시트 음력변환 2014.11.11 17849
595 [Docs]스프레드시트 Google Spreadsheet (Docs) 에서 우리은행 환율정보 이용하기 2014.11.11 29867
594 Excel 엑셀 여러가지 기능 2014.11.10 5009
593 Excel Google 스프레드시트 함수 2014.10.04 7164
592 Server XE DB 튜닝 2014.09.13 4375
591 Excel 배열수식 다중조건의 일치하는 값 불러 오기 2014.08.20 14175
590 Excel 오피스 2003, 2007, 2010... 삭제할 수 없을 때 제거 방법 2014.07.31 6878
589 컴퓨터잡담 구글 문서도구 스프레드시트로 바코드 입력하기 2014.07.19 4664
588 컴퓨터잡담 동영상 자르기 프로그램 file 2014.04.14 2704
587 AutoHotKey ahk) autohotkey controlgettext 이름을 마우스커서에 졸졸 따라다니게 하기 file 2014.04.01 12153
586 AutoHotKey 엑셀 셀 복사하기(복사제한된 엑셀등) 1 file 2014.04.01 7778
585 WindowsTip 인터넷 익스플로러 속도개선 프로그램 file 2014.03.26 4764
584 WindowsTip 스마트폰으로 오실로스코프 사용하기(App:OsciPrime Oscilloscope Legacy) file 2013.12.27 23297
583 WindowsTip Windows-XP 의 [Prefetch] 폴더에 대하여[C:\WINDOWS\Prefetch] 2013.12.04 24630
582 WindowsTip 탐색기로 ftp 폴더 바로열기 file 2013.12.03 19640
581 AutoHotKey ahk) 오토핫키 콤보박스 제어하기 file 2013.10.30 38146
580 AutoHotKey autohotkey) 오토핫키에서 자주쓰는 함수모음 2013.10.30 33652
579 AutoHotKey ahk) autohotkey 엑셀(Excel)에서 행값 증가시키기 2013.10.30 37410
578 AutoHotKey ahk) autohotkey 글자 자르기 방법 2013.10.30 34636
Board Pagination Prev 1 ... 15 16 17 18 19 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소