使用 PHP 逻辑的 XHR 请求的 Amp Form 问题(2 个版本有警告)

Amp Form issue with XHR request using PHP logic (2 versions with caveats)

我是不是做错了?

添加了 2 个代码示例!

对于这里的其他人来说可能很简单,我是 Amp html 和小胡子的新手,我在创建带有表单的 AMP 页面时遇到了令人沮丧的问题,但它几乎就在那里!

我必须重写几次,结果总是一样!我试图始终 return 通过表单提交正确的值,然后从数据库中提取,它只在页面刷新时第二次工作,即 * 按 f5 并再次尝试,否则它显示相同的内容.

它基本上用从数据库中 return 编辑的内容加载 div,无论它是否存在。

我认为问题出在会话上,我必须创建一个成功和错误变量来显示不同的内容,具体取决于数据库中是否存在数据,因为 XHR 响应总是成功的,除非发生某些事情破产了。

无论我在哪里设置会话未设置值,它要么什么都不做,要么使请求不起作用。

基于会话的示例:

<?php
session_start();
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: http://www.example.com");
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");

include_once('../includes/dbcon.php');
if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//remove out any spaces from $_post value
$value = str_replace(" ", "", $_POST['value']);
//make session the same as $_post value
$_SESSION["value"] = $value;
$value = $_SESSION["value"];
//check the db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists
              $_SESSION['msg'] = 'success';
                $output = $_SESSION['msg'];
                  echo json_encode($output);
            } 
} else {   
          // value does not exist
              $_SESSION['msg'] = 'error';
                 $output = $_SESSION['msg'];
                    echo json_encode($output);
       }
} else { //show page
include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>
  <h1>Check value.</h1>

    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>
        <label>
          <span>Check VALUE</span>
            <input type="text" name="value" required>
        </label>
            <input type="submit" value="Check">
      </fieldset>    
<div submit-success>
<template type="amp-mustache">
<?php    
          $response = $_SESSION['msg'];
        //echo $response .' ( '.$_SESSION['value'] .' ) ';  //test the session value returned
          if($response==='success') {
              echo 'Value already exists! do something here';
            } else if($response==='error') {
              echo 'Value does not exist! do something here';    
          }
?> 
</template>
</div>
<div submit-error>
<template type="amp-mustache">
  Something has gone wrong! (todo) If there is no response from xhr request then this error is displayed.
 </template>
 </div>
</form>
<?php include_once('includes/footer.php');
 }
 ?>

下面使用 amp-mustache 的原始版本,工作(有点)正常但不可能且无用,因为我无法从错误或成功消息向浏览器呈现 html 或操作或比较 mustache 标签PHP逻辑。

一定有可能... 例如 return 返回 json 数组,其中显示:

"Success! Value found click here: <a href="#">link</a>"

不是html所以不可能添加按钮等

这就是我检查值后需要完成的全部工作。

使用小胡子标签的版本

<?php
    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: http://www.example.com");
    header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
    header("Cache-Control:private");
    include_once('../includes/dbcon.php');

if(isset($_POST['value'])){
$value = isset($_POST['value']) ? $_POST['value'] : '';
//json
header("Content-Type: application/json");
//take out any spaces from the value first
$value = str_replace(" ", "", $_POST['value']);
//check db
$query = $db->prepare("SELECT * FROM posts WHERE value = '" . $value . "'");
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
if( $query->rowCount() > 0){
    foreach($rows as $row) {
         // value exists   
        echo json_encode(array('value'=>'My success message.'));
            } 
} else {   
          // value does not exist
        echo json_encode(array('value'=>'error.<a href="#">test</a>')); //does not display as html          
       }
} else { //show page

 include_once('includes/header.php');  //includes the amped form and mustache.js files etc
?>
  <h1>Check value.</h1>
    <form method="POST" action-xhr="//www.example.com/test" target="_blank">
      <fieldset>
        <label>
          <span>Check Value</span>
            <input type="text" name="value" required>
        </label>
            <input type="submit" value="Check">
      </fieldset>    
<div submit-success>
<template type="amp-mustache">
  {{value}}
</template>
</div>
    <div submit-error>
      <template type="amp-mustache">
          Something has gone wrong! (todo) If no response from xhr request then this error is displayed.
      </template>
    </div>
  </form>
<?php include_once('includes/footer.php');
  }
?>

我是个白痴,我想出了小胡子的方法(方法 2),我不敢相信我没有尝试过 - 我猜这是一份不涉及编程的日常工作!

只需将两项检查更改为:

 //success part
 $url="http://example.com/success-page";
 $title="my success title tag text";
 echo json_encode(array(
'value'=>'My <strong>success</strong> message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags

 //error part
 $url="http://example.com/error-page";
 $title="my error title tag text";
 echo json_encode(array(
'value'=>'My error message',
'url'=> $url,
'title' => $title
)); // add more variables to build up the JSON array and display them as mustache tags

最后将小胡子标签部分更改为:

{{{value}}} <a href="{{url}}" title="{{title}}">Click me</a>

3 个大括号取消转义简单的 HTML 标签。