概述
解决子域和主域的cookie问题:
function GetCookieDomain() {
var host = location.hostname;
var ip = /^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$/;
if (ip.test(host) === true || host === 'localhost') return host;
var regex = /([^]*).*/;
var match = host.match(regex);
if (typeof match !== "undefined" && null !== match) host = match[1];
if (typeof host !== "undefined" && null !== host) {
var strAry = host.split(".");
if (strAry.length > 1) {
host = strAry[strAry.length - 2] + "." + strAry[strAry.length - 1];
}
}
return '.' + host;
}
支持本地环境(仅判断localhost)、host为ip地址、中文域名、常规域名。如下图所示:
调用很简单,写了个示例:
document.cookie = cname + "=" + cvalue + "; expires=" + expires + "; domain=" + GetCookieDomain() + "; path=/";
最后
以上就是喜悦仙人掌为你收集整理的js创建cookie时获取一级域名设置domain解决跨域问题的全部内容,希望文章能够帮你解决js创建cookie时获取一级域名设置domain解决跨域问题所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复