<form id="formdata" >
<label>
会话Cookie:<input type="radio" class="radio" id="option1" checked="checked" name="radio" value='true'>
<br/>
持久Cookie:<input type="radio" class="radio" id="option2" name="radio" value='false'>
</label>
<button id="submit" type="submit">提交</button>
</form>
- 引入jquery 和ajax
<script src="/jquery/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
- 用ajax像后端发送请求获得用户之前设置
let cookieConfig = null
$.ajax({
type: "GET",
url: "http://localhost:8080/getConfig",
async: false,
success: function (data) {
cookieConfig = data
}
})
注意事项
- 如果后端项目是spring boot 或者sprig时,处理请求的方法上要加上 @CrossOrigin注解,不然会报跨域请求问题
- 加载用户之前所作的配置
var radios=$("input[name='radio']");
if (cookieConfig === true ){
radios.eq(0).attr("checked", true);
}
else {
radios.eq(1).attr("checked", true);
}
- 当用户点击提交的时候将用户所作的配置发送给后端
$("#submit").click(function () {
let a= $('input[name="radio"]:checked');
cookieOption = a.attr("id") === "option1";
data = {cookieOption: cookieOption}
$.ajax({
type: "GET",
data: data,
url: "http://localhost:8080/setConfig",
async: false,
success: function (data) {
alert(cookieOption)
}
})
})
完整代码
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Config</title>
</head>
<body>
<form id="formdata" >
<label>
会话Cookie:<input type="radio" class="radio" id="option1" checked="checked" name="radio" value='true'>
<br/>
持久Cookie:<input type="radio" class="radio" id="option2" name="radio" value='false'>
</label>
<button id="submit" type="submit">提交</button>
</form>
</body>
<script src="/jquery/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script >
let cookieConfig = null
let cookieOption
$.ajax({
type: "GET",
url: "http://localhost:8080/getConfig",
async: false,
success: function (data) {
cookieConfig = data
}
})
var radios=$("input[name='radio']");
if (cookieConfig === true ){
radios.eq(0).attr("checked", true);
}
else{
radios.eq(1).attr("checked", true);
}
$("#submit").click(function () {
let a= $('input[name="radio"]:checked');
cookieOption = a.attr("id") === "option1";
data = {cookieOption: cookieOption}
$.ajax({
type: "GET",
data: data,
url: "http://localhost:8080/setConfig",
async: false,
success: function (data) {
alert(cookieOption)
}
})
})
</script>
</html>