Javascript Not Setting Cookies



我正在尝试使用Javascript设置cookie。直到最近,当我开始获取cookie值的null时,这段代码一直在工作。我真的不确定是什么原因导致了这一切。这是我的HTML:

<div class="w3-container w3-center" style="align-content:center;">
<br>
<br>
<h1 class="w3-center w3-jumbo">Find a Fruit Here</h1>
<form method="post" name="input-form" id="input-form" class="w3-center w3-mobile">
<h4 class="w3-center" style="max-width:1000px;align-content:center;">
<label>Address</label>
</h4>
<input id="input-address" style="max-width:300px;margin-left:auto;margin-right:auto" class="w3-center w3-input w3-border" name="Address" placeholder="123 45th Street, City, State" required>          

<h4 class="w3-center" style="max-width:1000px;">
<label>Fruits(at least one)</label>
</h4>
<input id="input-items" style="max-width:300px;margin-left:auto;margin-right:auto" class="w3-center w3-input w3-border" name="Items" placeholder="Apples, bananas, etc." required>
<h4>
<button style="max-width:250px;margin-left:auto;margin-right:auto" class="w3-button w3-black w3-round w3-hover-light-grey w3-center" type="submit" onclick="cookies()">
Search
</button>
</h4>
</form>      
<br>
</div>

这是我的Javascript。我添加了一个日志行进行测试,但它从未打印到控制台,所以我认为调用该函数可能有问题。

<script>
function cookies() {
document.getElementById("input-form").submit();
document.cookie = "address=" + document.getElementById("input-address").value.replaceAll(",", "/");
document.cookie = "items=" + document.getElementById("input-items").value.replaceAll(",", "/");
}
</script>

非常感谢您的帮助!!我不知所措。

编辑:我正在使用Javalin访问Java程序中的cookie,这就是我看到它们为空的地方。我用Javalin呈现文档,然后尝试访问cookie,然后得到一个NullPointerException。这是Java代码:

app.get("/search", ctx -> ctx.render("/donation-find.html"));
app.post("/search", ctx -> {
ctx.render("/donation-find.html");
address = ctx.cookie("address").replaceAll("/", ",");
String[] temp = ctx.cookie("items").split("/");
}       

您在更新Javascript上的cookie之前提交表单。所以实际的POST请求是在cookie更新之前发送的
我认为你应该只做

function cookies() {
document.cookie = "address=" + document.getElementById("input-address").value.replaceAll(",", "/");
document.cookie = "items=" + document.getElementById("input-items").value.replaceAll(",", "/");
}
document.getElementById("input-form").submit();

我认为这会有所帮助
我不知道它以前是如何工作的
最好的猜测是它提取了旧的会话cookie

为了澄清起见,我最终使用了一种完全不同的数据传输方法来解决这个问题。我没有使用cookie,而是使用Javalin内置的方法formParam(key)来访问发布到表单的数据

最新更新