document.cookie()函数在Javascript中不起作用



当用户在文本框中输入时,我试图在JavaScript中设置cookie,但它似乎不起作用。当我试图提醒或安慰日志时,我会得到"价值请帮我做这件事。

HTML代码:

<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">
<input type="text" name="userName">
<input type="submit" value="Register">
</form>

JS代码:

function storeInHidden1(){
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var queryStringDetails = urlParams.get("userName");
document.cookie = "name=" + queryStringDetails;
alert(document.cookie);
}

问题

设置类似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,因为您的代码中没有设置example.com/index.html上的window.location.search

接下来,根据表格中的action="confirm.html",所有数据都与GET请求一起发送到(例如(example.com/confirm.html。该url现在具有?userName=JohnDoe的参数。如果你现在在这个页面上运行storeInHidden1,你实际上会在cookie中获得一些内容。

解决方案

为了将用户名保存在index.html上的cookie中,您只需要更改storeInHidden1中的代码。您可以直接从带有document.getElementsByName("userName")[0].value的表单中获取用户名,而不是从url中获取用户名。完整的代码可以在下面找到:

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>

最新更新