• Js跨一级域名同步cookie


    1. 纯Js同步两个域名下的cookie

    document.cookie = "name=" + "value;" + "expires=" + "datatime;" + "domain=" + "" + "path=" + "/path" + "; secure";
    //name     Cookie名字
    //value    Cookie值
    //expires    有效期截至(单位毫秒)
    //path    子目录
    //domain    有效域
    //secure    是否安全

    拿淘宝与天猫举例,淘宝登录后跳转到天猫页面,天猫页面有一个iframe,请求任意页面

    <iframe src='http://localhost:14373/test/Index' width='100' height='100' style="display:none"></iframe>

    淘宝页面中js获取当前页面的cookie并作为参数跳转回天猫页面

    window.location = "http://localhost:20272/GetCookie/Index?" + document.cookie;

    天猫页面获取url中的地址并将cookie写入本域名下

     var url = window.location.toString();//获取地址
     var get = url.substring(url.indexOf("liuph"));//获取变量和变量值
     var idx = get.indexOf("=");//获取变量名长度
     if (idx != -1) {
         var name = get.substring(0, idx);//获取变量名
         var val = get.substring(idx + 1);//获取变量值
         setCookie(name, val, 1);//创建Cookie
     }

    2. 经过后台处理同步cookie

    天猫页面直接请求淘宝的后台方法

    $.ajax({
            type: "GET",
            dataType: 'jsonp',
            jsonp: 'jsonp_callback',
            url: 'http://localhost:14373/test/GetString?cookie=?',
            success: function (da) {
                alert(da.name + "|" + da.value);
            }, error: function (){
                    alert("ERROR");
            }
    });

    淘宝后台代码

    public void GetString()
    {
            HttpCookie cookie = Request.Cookies["liuph"];
            var response = HttpContext.Response;
            response.ContentType = "text/json";
            string str = Request.QueryString["cookie"];//JS接受变量名
            response.Write(str + "({"name":" + """ + cookie.Name + """ + ","value":" + """ + cookie.Value + ""})");//返回数据
    }

    ok,同步结束

  • 相关阅读:
    MySQL 事务 清明
    ElasticSearch增删改查
    WinDbg常用命令系列内存查看d*
    WinDbg常用命令系列内存数据显示和对应符号显示d*s(dds、dps、dqs)
    WinDbg常用命令系列!heap
    WinDbg !teb
    Nodejs Stream(流)
    Nodejs 回调函数
    Vertx 简单介绍
    创建第一个应用Nodejs应用
  • 原文地址:https://www.cnblogs.com/zhhying/p/4167703.html
Copyright © 2020-2023  润新知