如何获取Cookie表单输入

时间:2018-11-12 08:19:40

标签: javascript html

我需要创建一个包含cookie的网站进行学习 如何获取Cookie表单输入。如果checkcookie不是数据,则迫使用户在输入中尝试不输入警报提示

<script>
function getCookie(c_name) {
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length+1;
      c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) 
        c_end = document.cookie.length
      return decodeURIComponent(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}
 
function setCookie(c_name, value,expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie = c_name+ "=" +encodeURIComponent(value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}


function checkCookie() {
	var inputcookie = document.getElementById("inpu-firstname").value;
    var user=getCookie("username");
    if (user != "") {
		alert("Welcome again " + user);
    }else {
	   document.cookie = "username"+inputcookie;
       if (user != "" && user != null) {
           setCookie("username", user, 30);
		   }
       }
}
</script>
<input text="text" class="form-control" id="submitted-firstname" name="submitted" onchange="setCookie();checkCookie();">
<button type="submit" class="btn btn-warning" id="senddata" onclick="setCookie();checkCookie();"><span class="w-submit">Submit</span></button>

0 个答案:

没有答案