구글 AMP – Form

4 min read

이 글에서는 구글 AMP에서 form을 사용하는 방법을 설명합니다.

form 태그는 표준 HTML과 동일하게 유지됩니다. AMP는 form 사용에 특별한 제한을 추가했습니다. 이로 인해 form 실행을 위해 amp-form 자바스크립트 파일을 추가해야 합니다.

amp-form 용 스크립트

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

AMP 페이지에서 form을 사용하려면 .html 파일에 위의 스크립트를 포함해야 합니다. amp-form 자바스크립트 파일은 form 제출을 위해 httpxmlhttprequest를 지원합니다. HTTP 요청을 사용하면 페이지가 다시 로드되고 xmlhttprequest를 사용하면 페이지가 다시 로드되지 않고 ajax 요청처럼 작동합니다.

AMP의 Form 태그

For xmlhttprequest :
<form method="post" class="p2" action-xhr="submitform.php" target="_top">
//Input fields here
</form>

For http :
<form method="post" class="p2" action="submitform.php" target="_top">
//Input fields here
</form>

Amp-form은 양식이 제출될 때 오류 및 성공을 처리하기 위해 submit-errorsubmit-success과 같은 특수 속성을 제공합니다.

예제

amp-form의 예는 다음과 같습니다.

<!doctype html>
<html ⚡ lang="ko">
<head>
  <meta charset="utf-8">
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <title>Google AMP - Form</title>
  <link rel="canonical" href="https://googleblogamp.blogspot.com/2021/01/google-amp-form.html">
  <meta name="viewport" content="width=device-width,minimum-scale=1">
  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
  <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
  <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
  <style amp-custom>
    form.amp-form-submit-success [submit-success],
    form.amp-form-submit-error [submit-error]{
      margin-top: 16px;
    }
    form.amp-form-submit-success [submit-success] {
      color: white;
      background-color:gray;
    }
    form.amp-form-submit-error [submit-error] {
      color: red;
    }
    form.amp-form-submit-success.hide-inputs > input {
      display: none;
    }
  </style>
</head>
<body>
<h3>Google AMP - Form</h3>
<form method="post" class="p2" action-xhr="submitform.php" target="_top">
  <p>AMP - Form Example</p>
  <div>
    <input type="text" name="name" placeholder="Enter Name" required><br/><br/>
    <input type="email" name="email" placeholder="Enter Email" required><br/><br/>
  </div>
  <nput type="submit" value="Submit">
  <div submit-success>
    <template type="amp-mustache">
      Form Submitted! Thanks {{name}}.
    </template>
  </div>
  <div submit-error>
    <template type="amp-mustache">
      Error! {{name}}, please try again.
    </template>
  </div>
</form>
</body>
</html>

결과

위에 표시된 코드를 실행하면 아래와 같은 결과를 찾을 수 있습니다.

이제 세부 정보를 입력하고 제출 버튼을 클릭합니다. 표시되는 출력 화면은 다음과 같습니다.

데이터 바인딩에 amp-mustache를 사용했습니다. 양식은 action-xhrie xmlhttprequest를 사용하여 양식을 제출합니다. json 형식으로 데이터를 반환하는 submitform.php 파일을 사용했습니다.

<form method="post" class="p2" action-xhr="submitform.php" target="_top">
</form>

submitform.php

<?php
if(!empty($_POST)){
  $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") ."://$_SERVER[HTTP_HOST]";
  header("Content-type: application/json");
  header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
  header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
  $myJSON = json_encode($_POST);
echo $myJSON;
}
?>

양식이 xmlhttprequest를 사용하여 작동하려면 CORS 사양에 따라 헤더를 추가해야 합니다. submitform.php에 추가된 응답 헤더의 세부 사항은 다음과 같습니다.

양식이 작동하려면 AMP-Access-Control-Allow-Source-Originamp-access-control-allow-source-origin:http://localhost:8080 값이 있는 access-control-expose-headers와 같은 헤더를 추가해야 합니다.

우리는 PHP 파일과 아파치 서버를 사용하고 있습니다. php 파일에 아래와 같이 필수 헤더를 추가했습니다.

<?php
if(!empty($_POST)){
  $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") ."://$_SERVER[HTTP_HOST]";
  header("Content-type: application/json");
  header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
  header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
  $myJSON = json_encode($_POST);
  echo $myJSON;
}
?>

일반적인 http 요청을 사용하는 경우 페이지는 아래와 같이 다시 로드됩니다. http 요청의 경우 다음과 같은 양식을 사용했습니다.

<form method="GET" class="p2" action="submitform.php" target="_top">
</form>

예제

더 나은 이해를 위해 다음 코드를 관찰하십시오.

<!doctype html>
<html ⚡ lang="ko">
<head>
  <meta charset="utf-8">
  <script async src="https://cdn.ampproject.org/v0.js"></script>
  <title>Google AMP - Form</title>
  <link rel="canonical" href="https://googleblogamp.blogspot.com/2021/01/google-amp-form.html">
  <meta name="viewport" content="width=device-width,minimum-scale=1">
  <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
  <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
  <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
  <style amp-custom>
    form.amp-form-submit-success [submit-success],
    form.amp-form-submit-error [submit-error]{
      margin-top: 16px;
    }
    form.amp-form-submit-success [submit-success] {
      color: white;
      background-color:gray;
    }
    form.amp-form-submit-error [submit-error] {
      color: red;
    }
    form.amp-form-submit-success.hide-inputs > input {
      display: none;
    }
  </style>
</head>
<body>
<h3>Google AMP - Form</h3>
<form method="GET" class="p2" action-xhr="submitform.php" target="_top">
  <p>AMP - Form Example</p>
  <div>
    <input type="text" name="name" placeholder="Enter Name" required><br/><br/>
    <input type="email" name="email" placeholder="Enter Email" required><br/><br/>
  </div>
  <nput type="submit" value="Submit">
  <div submit-success>
    <template type="amp-mustache">
      Form Submitted! Thanks {{name}}.
    </template>
  </div>
  <div submit-error>
    <template type="amp-mustache">
      Error! {{name}}, please try again.
    </template>
  </div>
</form>
</body>
</html>

위에 표시된 코드를 실행하면 아래와 같은 결과를 찾을 수 있습니다.

방문해주셔서 감사합니다. 즐거운 하루 되세요!

관심 있을 만한 글

  • Amp-selector는 옵션 메뉴를 표시하는 amp 구성 요소이며 사용자가 옵션 중에서 선택할 수 있습니다. 표시되는 옵션은 텍스트, 이미지 또는 기타 amp 구성 요소 일 수 있습니다. 이 글에서는 이에 대해 자세히 설명하겠습니다. amp-selector를 사용하려면 다음 자바스크립트 파일을 포함해야 …
  • Amp-story는 사용자가 스토리에 계속 참여할 수 있도록 콘텐츠를 표시하는 데 사용되는 amp 구성 요소입니다. 예를 들어 브랜드에 대해 소개하는 일련의 이미지를 사용할 수 있습니다. amp-story로 작업하려면 아래와 같이 스크립트를 포함해야 합니다. <script async cust…
  • AMP Datepicker는 사용자가 날짜를 선택할 수 있는 페이지에 달력을 표시하는 amp 구성 요소입니다. AMP datepicker는 정적 달력처럼 표시되거나 입력 선택에 따라 버튼 클릭으로 표시될 수 있습니다. amp-date-picker를 작동시키려면 페이지에 다음 스크립트를 추가해야 합니다.…
  • Amp Date countdown이라는 또 다른 amp 구성 요소는 주어진 날짜까지의 일, 시간, 분, 초를 표시하는 데 사용됩니다. 날짜 표시는 선택한 로케일에 따라 수행될 수 있습니다. 기본값은 en (영어)입니다. Amp-date-countdown은 데이터 렌더링에 amp-mustache 템플릿을 사…
  • Amp 태그 amp-fit-text는 디스플레이를 렌더링하기에 공간이 충분하지 않은 경우 글꼴 크기를 줄입니다. 이 글에서는 이 태그에 대해 자세히 설명합니다. amp-fit-text가 작동하도록 하려면 다음 스크립트를 추가해야 합니다. <script async custom-element="am…
  • Amp의 Link 태그는 사용 가능한 amp 및 non-amp 페이지에 대해 Google 검색 엔진에 알리는 데 사용됩니다. 이 글에서는 Link 태그와 관련된 측면과 구글이 amp-page 및 non amp-page에 대해 결정하는 방법에 대해 자세히 설명하겠습니다. AMP 페이지 발견 https…

댓글 쓰기