[英]best way to pass a variable between two php pages
需要將一個變量從index.php
傳遞給edit.php
。
該變量應該對訪問者不可見,因此不允許使用地址欄。
第一種方式 - 在index.php
使用帶有action
屬性的表單 - edit.php
。
使用表單的問題是每次刷新edit.php
時edit.php
出現有關重新提交的警告。
第二種方式 - 在index.js
上使用 ajax 調用來更改 php 端的會話變量。
使用 ajax 的缺點是一條額外的路徑 - 首先轉到server side
(更改 php) - 然后到client side
(成功函數獲取新值) - 然后再到服務器端(使用新變量轉到edit.php
) .
什么是正確的方法?
有沒有這樣的簡單方法:
location.href = 'edit.php', set x = 5
在edit.php
上得到這個:
echo $x
(結果 5);
您可以在index.js
創建一個自定義 cookie edit.php
加到document.cookie
,當對edit.php
發出請求時,它將可用。
索引.js
const custom_cookie = "x=5";
document.cookie = custom_cookie;
.....
window.location = 'edit.php';
編輯.php
$cookie_name = 'x';
echo $_COOKIE[$cookie_name]
另一種方法是使用 PHP Sessions。
//index.php
$_SESSION['varname'] = $var_value;
//edit.php
$var_value = $_SESSION['varname'];
記得運行session_start()
; 在您嘗試訪問 $_SESSION 數組之前,以及在將任何輸出發送到瀏覽器之前,在這兩個頁面上的語句。
如果參數必須在 UI 中保持不可見(即不在地址欄中)並且您需要避免由於頁面重新加載而導致 POST 請求,則可以通過兩個請求來實現...
一個 AJAX POST 然后一個 GET,即
fetch('set-session-var.php', {
method: 'post',
body: 'x=5',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(res => {
if (res.ok) {
window.location = 'edit.php'
}
})
或使用Post / Redirect / Get模式,例如
<form action="set-session-var.php" method="post">
<!-- set the "x" value however and whenever you want -->
<button type="submit" name="x" value="5">Go</button>
</form>
// set-session-var.php
session_start();
$_SESSION['x'] = $_POST['x'];
header('Location: edit.php'); // omit this if using the AJAX version
使用餅干...
索引.php:
setcookie("x", 5);
編輯.php:
echo $_COOKIE["x"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.