1 回答

TA貢獻1111條經驗 獲得超0個贊
問題
像這樣設置一個cookie
document.cookie = "name=" + variable
根據w3schools 的說法,這是一種有效的方法。但是問題是您正在嘗試訪問不存在的 url 參數,這就是您的 cookie 為空的原因。假設example.com/index.html
你有以下形式:
<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
<input type="text" name="userName">
<input type="submit" value="Register">
</form>
onsubmit代碼運行storeInHidden1()試圖獲取window.location.search仍然為空的函數的函數,因為您的代碼中沒有任何內容設置window.location.searchon example.com/index.html。
接下來根據action="confirm.html"表格,所有數據都隨GET請求發送到(例如)example.com/confirm.html。這個 url 現在有 的參數?userName=JohnDoe。如果您現在要storeInHidden1在此頁面上運行,您實際上會在 cookie 中獲得一些內容。
解決方案
為了將用戶名保存在 cookie 中,index.html您只需更改storeInHidden1. 您可以直接從表單中獲取用戶名,而不是從 url 中獲取用戶名document.getElementsByName("userName")[0].value。完整的代碼可以在下面找到:
function storeInHidden1() {
var user = document.getElementsByName("userName")[0].value;
document.cookie = "name=" + user;
alert(document.cookie);
}
<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
<input type="text" name="userName">
<input type="submit" value="Register">
</form>
添加回答
舉報