cookie UrlParam 设置获取.js工具类

cookie设置获取工具类

  • cookie_utils.js

前端浏览器设置cookie并取值

var operator = "=";

function getCookieValue(keyStr){
    
    
	var value = null;
	var s = window.document.cookie;
	var arr = s.split("; ");
	for(var i=0; i<arr.length; i++){
    
    
		var str = arr[i];
		var k = str.split(operator)[0];
		var v = str.split(operator)[1];
		if(k == keyStr){
    
    
			value = v;
			break;
		}
	}
	return value;
}

function setCookieValue(key,value){
    
    
	document.cookie = key+operator+value;
}
  • html中的应用(设置)
//如果登录成功,就把token存储到cookie
setCookieValue("token",vo.msg);
//将用户昵称和用户头像的路径保存在cookie
setCookieValue("userId",vo.data.userId);
setCookieValue("username",vo.data.username);
setCookieValue("userImg",vo.data.userImg)
  • html中的应用(获取)
<script type="text/javascript">
			
			var vm = new Vue({
      
      
				el:"#container",
				data:{
      
      
					username:"",
					userimg:"",
					isLogin:false,
				},
				created:function(){
      
      
					//从cookie中获取token、username、userImg
					var token = getCookieValue("token");
					if(token !=null && token !=""){
      
      
						this.isLogin = true;
						this.username = getCookieValue("username");
						this.userimg = getCookieValue("userImg");
					}
				}
			});
</script>

获取请求参数工具类

  • cookie_utils.js

获取url地址中的请求参数

function getUrlParam(key){
    
    
	var url = decodeURI( window.location.toString() );
	var arr = url.split("?");
	if(arr.length>1){
    
    
		var params = arr[1].split("&");
		for(var i=0; i<params.length; i++){
    
    
			var param = params[i];  //"pid=101"
			if(param.split("=")[0] == key ){
    
    
				return param.split("=")[1];
			}
		}
	}
	return null;
}
  • html中的应用
<script type="text/javascript">	
			var vm = new Vue({
      
      
				el:"#container",
				data:{
      
      
					tips:"",
					returnUrl:null,
					pid:0,
					sid:0,
					num:1
				},
				created:function(){
      
      
		//1.当从商品详情页跳转到登录页面的时候,获取并显示提示信息(url)
					this.tips = getUrlParam("tips");
					
					//2.获取到returnUrl 、 pid 、sid
					this.returnUrl = getUrlParam("returnUrl");
					this.pid = getUrlParam("pid");
					this.sid = getUrlParam("sid");
					this.num = getUrlParam("num");
			});
</script>

猜你喜欢

转载自blog.csdn.net/qq_45246098/article/details/121838161