簡體   English   中英

使用PHP的AMP表單POST

[英]Amp form POST using PHP

我正在使用Amp發布表單,並使用PHP進行處理。 我收到以下錯誤:

表單提交失敗::響應必須包含AMP-Access-Control-Allow-Source-Origin標頭

代碼:

<?php
if(isset($_POST\['submitlogin'\]))
{
    $name = isset($_POST\['name'\]) ? $_POST\['name'\] : '' ;
    $output = \[
            'name' => $name
    \];
header("Content-type: application/json");
header("Access-Control-Allow-Credentials: true");
header("AMP-Same-Origin: true");
header("Access-Control-Allow-Origin: *.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: *");
#header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
echo json_encode($output);
die();

}
?>

<!doctype html>
<html amp>
<head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <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.1.js">
    </script>
    <link rel="canonical" href="localhost">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-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>
  <title>AMP form</title>
</head>
<body>
<form method="post" action-xhr="#" target="_top">
    Name:<input type="text" name="name" />
    <input type="submit" name="submitlogin" value="Submit" />
</form>
<div submit-success>
    <template type="amp-mustache">
        Success! Thanks for trying the
        <code>amp-form</code> demo! The name submited was {{name}}
    </template>
</div>
</body>enter code here
</html>

我已經包含所有標頭,我面臨的唯一問題是使用Apache將站點托管在localhost上。 請幫我做些允許localhost上的amp頭的工作。

嘗試將以下行添加到您的.htaccess中:

Header set Access-Control-Allow-Origin "*"
Header set AMP-Access-Control-Allow-Source-Origin "https://yourdomain.com"

我在搜索相同答案時發現了您的問題。 在調試請求時,我注意到以下查詢字符串已添加到請求中

?__amp_source_origin=http%3A%2F%2Flocalhost%3A8080

並通過添加

header('AMP-Access-Control-Allow-Source-Origin: '.'http://'. $_SERVER['HTTP_HOST']);

對於回應,AMP不再抱怨。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM