Set and check Javascript cookie based on url query string

扶醉桌前 提交于 2019-12-25 03:38:05

问题


I'm trying to set up a system on my site so that users who come through a custom link get tagged with a cookie that triggers a specific code to replace the default part of a signup form. The desired result is, in this example, for someone coming to http://example.com/?=mylink1 getting tagged with a cookie that changes the "value" attribute in any inputs with id #xcode to "X190". What I have so far:

Create cookie from query string:

  function cookieQuery() {
            var url = window.location.href;
            if(url.indexOf('?' + mylink1) = 1)
                document.cookie="cookie1";
    }

Check cookie and if true change attribute value with Jquery, if no cookie, do nothing:

function readCookie(cookie1) {
    var nameEQ = cookie1 + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) 

            $("#xcode").attr("value","X190");
    }
    return null;
}   

I appreciate any help figuring this out!


回答1:


You don't need to use a cookie unless you need to persist data on the users computer, you can use the url parameter by itself to change the form.

//page URL http:somewhere.com/index.html?foo=bar&baz=boaz var url = window.location.href;

//This function puts all of the params into a js object
function getParams(u){
    var theURL = u; 
    var params = {}; 
    var splitURL = theURL.split('?'); 
    if (splitURL.length>1 ){ 
        var splitVars = splitURL[1].split('&'); 
        for(var i = 0; i < splitVars.length; i++){ 
            splitPair = splitVars[i].split('='); 
            params[splitPair[0]] = splitPair[1]; }

        return params;
    }
    return false;
}

params = getParams(url);

//Check if there are any params
if (params) {
    var foo = params.foo;
    //Use foo to make decision here
}


来源:https://stackoverflow.com/questions/25853799/set-and-check-javascript-cookie-based-on-url-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!