フォームデータを配列に投稿することができましたが、topics.php
ページから(リダイレクトされていないURLを手動で入力して)戻ると、配列がリフレッシュされ元の配列に戻ります。HTMLフォームデータをPHP配列に永久に投稿するにはどうすればよいですか?
フォームデータをアレイに永久に追加するにはどうすればよいですか?手動でページをリダイレクトする必要があると思われますが、割り当ての一部として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);
?>
「セッション」をご覧ください。 – arkascha