根据网址查询字符串设置和检查Javascript Cookie [英] Set and check Javascript cookie based on url query string
问题描述
我正在尝试在我的网站上建立一个系统,以便通过自定义链接访问的用户使用Cookie标记,该Cookie会触发特定代码来替换注册表单的默认部分.在此示例中,期望的结果是某人访问 http://example.com/?=mylink1用cookie标记,该cookie会将ID为#xcode的所有输入中的"value"属性更改为"X190".到目前为止,我所拥有的:
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:
从查询字符串创建cookie:
Create cookie from query string:
function cookieQuery() {
var url = window.location.href;
if(url.indexOf('?' + mylink1) = 1)
document.cookie="cookie1";
}
检查cookie,如果为true,则使用Jquery更改属性值,如果没有cookie,则不执行任何操作:
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!
推荐答案
除非您需要将数据持久存储在用户计算机上,否则不需要使用cookie,您可以单独使用url参数来更改表单.
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.
//页面URL http:somewhere.com/index.html?foo = bar& baz = boaz var url = window.location.href;
//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
}
这篇关于根据网址查询字符串设置和检查Javascript Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!