有一對夫婦的方式來處理這個問題。最常見的是通過處理表單數據並生成服務器端的HTML,但如果您願意,可以使用JavaScript在客戶端完成。
服務器端(PHP)技術
下面的例子示出了PHP溶液。這也可以通過ASP,JSP,& c來完成。如果您希望數據持續存在,您必須在page.php
(或基於所用語言的同等語言)上記錄它,並將其存儲在會話Cookie或數據庫中(具體取決於所需的持久性)。
索引。HTML
<form method="POST" action="page.php">
<input type="text" id="my_text" name="my_text" />
<input type="submit" />
</form>
page.php文件
<?php
/* the $_REQUEST will get the variable regardless of whether
* it is sent via POST or GET. You may wish to use $_POST
* instead, for security reasons. */
echo "<h1>" . $_REQUEST["my_text"] . "</h1>";
?>
客戶端(JavaScript)技術#1
如果要使用JavaScript,你將需要存儲信息在網站上的其他頁面可以訪問的地方。這可能是一個cookie或本地存儲。在這種情況下,cookie可能是最簡單的(也是最可靠的)存儲技術。下面的jQuery示例顯示了該技術。
的index.html
<script type="text/javascript">
function store() {
var text = document.getElementById("my_text").value;
document.cookie = "text=" + text + "; path=/";
}
</script>
<form action="page.html" onsubmit="store()">
<input type="text" id="my_text" />
<input type="submit" />
</form>
page.html中
<h1 id="title"></h1>
<script type="text/javascript">
/* this just grabs the value of the first cookie for your site.
* if you use cookies elsewhere, you'll need to add logic to
* make sure you get the correct cookie. */
var text = document.cookie.split(";")[0].split("=")[1];
document.getElementById("title").innerHTML = text;
</script>
客戶端(JavaScript)技術#2
您還可以通過發送URL中的數據(使用GET而不是POST)來避免使用Cookie。我借用/修改了this blog中的代碼片段來演示該技術。
的index.html(無JavaScript的這個網頁上!)
<form method="GET" action="page.html">
<input type="text" id="my_text" name="my_text" />
<input type="submit" />
</form>
page.html中
<h1 id="title"></h1>
<script type="text/javascript">
function getUrlVars() {
var vars = {};
var url = decodeURIComponent(window.location.href.replace(/\+/g, '%20'));
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var text = getUrlVars()["my_text"];
document.getElementById("title").innerHTML = text;
</script>
沒有somehwere存儲的值(例如一個cookie)如何page.html中應該知道你輸入的內容在index.html上的形式? – j08691
只有該代碼全部在同一頁面上並且動作將設置爲「」 – Toumash