如何在PHP数组中永久发布HTML表单数据?

时间:2017-01-05 14:01:36

标签: php html arrays

我设法将表单数据发布到数组中,但是当我从topics.php页面返回时(通过键入url手动而不是重定向),数组会刷新并返回到原始数组

如何永久地将表单数据添加到阵列?我怀疑它与必须手动重定向页面有关,但是我必须在我的作业中包含header('Content-Type: application/json; charset=utf-8');,因此无法使用标题重定向。我是PHP的新手,所以情况可能并非如此。

我的代码:

topics.php

<?php
header('Content-Type: application/json; charset=utf-8');
$topics = array("Musical instruments", "Programming languages", "Varieties of pizza");
$newtopic = $_POST['newtopic'];
if( isset($_POST['newtopic']) )
{
    array_push($topics, $newtopic);
}
echo json_encode($topics);
?>

admin.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Admin Page</title>
  <meta name ="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js></script>

<style>
div.col-sm-6{
    font-size: 2em;
}
</style>

</head>
<body>

<div class="jumbotron text-center">
  <h1> Admin Page </h1>
  <p> A page to add to topics. </p>
</div>


<div class="container">
  <div class="row">
    <div class="col-sm-4">
      <div class="topic-container">
      <button name="topic-button" id="topic-button" type="button">Show Topics</button>
      <br></br>
      <h2>Topics:</h2>
      </div>
    </div>
    <div class="col-sm-4">
      <div class="form-container">
        <form action="topics.php" method="post">
        <h2>New Topic:</h2>
        <input type="text" name="newtopic">
        <input type="submit" value="Submit Topic">
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){
    $("#topic-button").click(function(){
        $.getJSON("topics.php", function(result){
            $.each(result, function(i, field){
                $(".topic-container").append(field + " ");
            });
        });
    });
});
</script>

</body>
</html>

编辑: 我已更改topics.php,因此会保存会话变量,但这仍然无法阻止数组刷新并返回原始数据。

<?php
session_start();
header('Content-Type: application/json; charset=utf-8');
$topics = array("Musical instruments", "Programming languages", "Varieties of pizza");
$_SESSION["newtopic"] = $_POST["newtopic"];
if( isset($_POST['newtopic']) )
{
    array_push($topics, $_SESSION["newtopic"]);
}
echo json_encode($topics);
?>

1 个答案:

答案 0 :(得分:1)

$_POST数据是您发送给服务器的请求的一部分。当您使用post方法提交表单时,此表单的数据随请求一起发送,但每个后续请求都会被遗忘。

您想要的是$_SESSION,这是一个变量,可以包含多个请求之间当前用户会话持续时间的数据。请记住,会话变量对每个访问者都是唯一的。