试图从表单中检索cookie,并仅以javascript显示他的信息



事实上,我是法国人,很抱歉我将要犯的错误。对于我的项目,我需要检索我表格中的信息(姓名、姓氏、电子邮件(,并使用cookie在另一个页面上显示信息。我对javascript不太了解,也不知道怎么做。

<form action="#" method="POST">
Nom : <input type="text" name="data">
Prénom : <input type="text" name="data">
Email : <input type="text" name="data">
<input type="submit" value="Validez">
</form>
<script>
function creerCookie(nom, valeur, jour){
if(jour) {
var date = new Date();
date.setTime(date.getTime()+(jour*24*60*60*1000));
var exp = '; expires='+date.toGMTString();
}
else{
var exp = '';
}
document.cookie = nom+'='+valeur+exp+';path=/';
}
function lireCookie(nom){
var nomEtEgal = nom + '=';
var cTableau = document.cookie.split(';');
for(var i= 0 ; i < cTableau.length; i++){
var c = cTableau[i];
while(c.charAt(0)==' '){
c = c.substring(1, c.length);
}
if(c.indexOf(nomEtEgal) == 0){
return c.substring(nomEtEgal.length, c.length);
}
}
return null
}
function supprimerCookie(nom){
creerCookie(nom,'', -1);
}
creerCookie('Cookie1',"Je suis un cookie", 7);
var affiche = document.getElementById('para');
affiche.innerHTML = 'Valeur :' + lireCookie('Cookie1');
</script>

使用localStorage会容易得多,下面是一个简短的演示:https://codepen.io/timotgl/pen/jOrdoMp

<form>
<p>
First name: <input type="text" name="firstName" />
</p>
<p>
Last name: <input type="text" name="lastName" />
</p>
<p>
Email : <input type="text" name="email" />
</p>
</form>
<button id="save">Save</button>
<script>
// Read input values from localStorage
let firstName = localStorage.getItem('firstName') || '';
let lastName = localStorage.getItem('lastName') || '';
let email = localStorage.getItem('email') || '';
// Find input elements
const firstNameInput = document.querySelector('input[name="firstName"]');
const lastNameInput = document.querySelector('input[name="lastName"]');
const emailInput = document.querySelector('input[name="email"]');
// Restore input values
firstNameInput.value = firstName;
lastNameInput.value = lastName;
emailInput.value = email;
// Save what the user types
firstNameInput.addEventListener('change', (event) => {
firstName = event.target.value;
});
lastNameInput.addEventListener('change', (event) => {
lastName = event.target.value;
});
emailInput.addEventListener('change', (event) => {
email = event.target.value;
});
// Write everything to localStorage if save button is clicked
const saveButton = document.querySelector('button#save');
saveButton.addEventListener('click', () => {
localStorage.setItem('firstName', firstName);
localStorage.setItem('lastName', lastName);
localStorage.setItem('email', email);
});
</script>

最新更新