如果声明为真,如何执行此JS代码?设置cookie

时间:2015-08-30 10:14:08

标签: javascript cookies setcookie getvalue

请帮我在js中找到以下的可靠解决方案:

1)我有来自referrer的URL,其中包含两个变量

2)我必须抓住 pdid puid 变量形成网址,并设置名称为POKUPON_DID和POKUPON_UID及其值的Cookie

3)如果URL不包含此变量,则将Cookie设置为未定义的主要问题。我需要你对corect IF语句的帮助。代码应该只预编码一次,如果URL中的变量存在...

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 
if($POKUPON_DID != emty){
    
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}

提前多多谢谢你!

1 个答案:

答案 0 :(得分:0)

您需要检查以下内容的未经阅读的内容: How to check for "undefined" in JavaScript?

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;

}

var $POKUPON_DID = getUrlVars()["pdid"];
var $POKUPON_UID = getUrlVars()["puid"];
 console.log($POKUPON_DID);
 console.log($POKUPON_UID);

if(typeof $POKUPON_DID != 'undefined'){
setCookie("POKUPON_DID",$POKUPON_DID,30);
setCookie("POKUPON_UID",$POKUPON_UID,30);
}