在我开始面对的问题之前,我想澄清一下我在做什么。
我有2页。
以下屏幕截图为restaurant.php
。您可以在说明下看到按钮Add Categories
,它会链接到categories.php
用户将使用以下步骤输入信息:
Add Categories
按钮categories.php
,用户需要填写该页面上的信息,然后点击save
restaurant.php
基本上,我要做的是保留用户在restaurant.php
categories.php
页面上输入的值
我的部分简化代码如下所示(忽略临时的上传图片代码)
restaurant.php
<?php
session_start();
if (isset($_POST['submit_button'])){
$title=sanitize($_POST['title']);
$description=sanitize_html($_POST['description']);
mysql_query("UPDATE restaurant SET title='$title', description='$description' WHERE id='$id'");
}
else{
$_SESSION['title'] = $_POST['title'];
$_SESSION['description'] = $_POST['description'];
}
?>
<script>
$('button').click(function() {
$.ajax({
type: "POST",
url: "categories.php",
data: 'title='+ title,
success: function(){
location.reload();
}
});
});
</script>
<form action="restaurant.php" method="post" enctype="multipart/form-data">
<label>Title</label>
<input type="text" name="title" value="<?php echo $_SESSION['title']; ?>">
<label>Description</label>
<textarea name="description" >
<?php echo $_SESSION['description']; ?>
</textarea>
<button><a href="categories.php">Add Categories</a></button>
<input class="button" name="submit_button" type="submit" value="Save Changes" />
</form>
我得到的是通过使用ajax在页面重新加载(在同一页面上)保留值,但我不确定如何在重定向到其他页面并返回到同一页面后保留该值。我接受其他方法,保证它有效。请提前帮助,谢谢。
答案 0 :(得分:0)
试试这个: -
<?php
if (isset($_POST['submit_button'])){
$title=sanitize($_POST['title']);
$description=sanitize_html($_POST['description']);
mysql_query("UPDATE restaurant SET title='$title', description='$description' WHERE id='$id'");
}
else{
if (isset($_COOKIE['title']) && isset($_COOKIE['description'])) {
$title = "value=".$_COOKIE['title'];
$description = $_COOKIE['description'];
}
else {
$title = "";
$description = "";
}
}
?>
<form action="restaurant.php" method="post" enctype="multipart/form-data">
<label>Title</label>
<input type="text" id="title" name="title" <?php echo $title; ?>>
<label>Description</label>
<textarea name="description" id="description" ><?php echo $description; ?>
</textarea>
<button type="button" id="addcategory" onclick="keepData();">Add Categories</button>
<input class="button" name="submit_button" type="submit" value="Save Changes" />
</form>
<script>
function keepData(){
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
createCookie('title', title, 1);
createCookie('description', description, 1);
window.location.href="categories.php";
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
//console.log('Cookie created! - '+name );
}
</script>