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
번호 분류 제목 날짜 조회 수
917 프로세스 프로세스 2 3 2011.02.07 312173
916 WindowsTip 윈도우 DLL 오류 해결방법 2013.01.23 192700
915 컴퓨터잡담 자바스크립트로 전송(submit) 버튼 누르기 3 2010.10.10 103612
914 컴퓨터잡담 hMailServer - 설치시 주의 핵심사항 1 2010.08.24 103065
913 컴퓨터잡담 북마크 링크 주소모음 2010.10.30 102936
912 컴퓨터잡담 엑셀 색깔 지정 함수 1 2010.07.28 65606
911 컴퓨터잡담 MYSQL 미 해결 과제 : Can't connect to MySQL server on 'localhost'(10055) 3 3 2009.11.21 64225
910 파이썬 파이썬에서 인식이 잘되는 OCR 종류 2023.09.15 63886
909 컴퓨터잡담 파이썬 request, beautifulshop으로 정액정보 받아오기 2023.09.29 63384
908 파이썬 한우경매낙찰 유튜브 영상의 이미지에서 특정 문자 가져와서 저장하기 2023.09.14 63132
907 컴퓨터잡담 CANON PRINTER ERROR CODE B203, B204 해결방법 2023.09.17 62792
906 컴퓨터잡담 php로 이미지를 mysql디비 저장하고 보여주는 소스 4 3 2009.10.17 62304
905 파이썬 파이썬 랜덤으로 문제풀기 #2 2023.10.04 62119
904 파이썬 파이썬 랜덤으로 시험문제 풀기 file 2023.10.04 59799
903 컴퓨터잡담 여러개의 엑셀파일을 하나로 합치기 2 2010.06.22 57361
902 컴퓨터잡담 오류 socket error #10061 connection 3 2 2010.09.25 53970
901 AutoHotKey AHK) AUTOKEY 웹페이지 열지않고 소스 가져오기 또는 로그인 하기 14 2012.05.12 52944
900 Visual C++ VBS) VBScript Telnet log save 2013.09.21 51926
899 파이썬 파이썬 requestsbeautifulsoup 으로 웹 input에 입력값 대입한 뒤 결과값 파일로 저장하기 2023.11.13 51160
898 컴퓨터잡담 H734GP 공유기 시스템로그 중 >>> Send Offer / Receive Discover / 2023.06.04 50967
Board Pagination Prev 1 2 3 4 5 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소