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

当用户在文本框中输入时,我试图在 JavaScript 中设置 cookie,但它似乎无法正常工作。当我尝试警报或 console.log 时。我得到“”值。请帮我解决这个问题。


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);

}


交互式爱情
浏览 247回答 1
1回答

catspeake

问题像这样设置一个cookiedocument.cookie&nbsp;=&nbsp;"name="&nbsp;+&nbsp;variable根据w3schools 的说法,这是一种有效的方法。但是问题是您正在尝试访问不存在的 url 参数,这就是您的 cookie 为空的原因。假设example.com/index.html你有以下形式:<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">&nbsp; <input type="text" name="userName">&nbsp; <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() {&nbsp; var user = document.getElementsByName("userName")[0].value;&nbsp; document.cookie = "name=" + user;&nbsp; alert(document.cookie);}<form action="confirm.html" id="interestForm" onsubmit="storeInHidden1()">&nbsp; <input type="text" name="userName">&nbsp; <input type="submit" value="Register"></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript