zoukankan      html  css  js  c++  java
  • php、asp.net关于后台设置的cookie前台JS获取时出现中文乱码问题解决

    .NET:

    在后台设置的中文cookie,可以先用HttpUtility.UrlEncode进行编码,在前台用JS获取cookie时用decodeURIComponent进行解码

    PHP:

    1. 详见 http://www.cnblogs.com/Byrd/archive/2011/06/23/2088358.html

    这种设置在IE上用没有问题,但在Firefox下中文出现乱码,借鉴.net下的解决方法对字符串进行urlencode编码

    2.

    首先PHP在用urlencode编码时要转换成utf-8再编码,然后设置cookie
     <?php

        $str = "国家主席";
        $test = iconv("GB2312","UTF-8",$str);

        setrawcookie("username",escape($_GET["username"]));
    ?> JS函数
    function URLdecode(str) {
        var ret = "";
        for(var i=0;i<str.length;i++) {
            var chr = str.charAt(i);
            if(chr == "+") {
                ret += " ";
            }else if(chr=="%") {
                var asc = str.substring(i+1,i+3);
                if(parseInt("0x"+asc)>0x7f) {
                    ret += decodeURI("%"+ str.substring(i+1,i+9));
                    i += 8;
                }else {
                    ret += String.fromCharCode(parseInt("0x"+asc));
                    i += 2;
                }
            }else {
                ret += chr;
            }
        }
        return ret;
    }
    js获取cookie:username = URLdecode(readCookie("username"));
     
  • 相关阅读:
    python uuid
    linux 修改时区
    Nginx 缓存命中率
    MongoDB oplog 详解
    MongoDB 复本集搭建
    复制集简介
    解决Python2.7的UnicodeEncodeError: 'ascii' codec can't encode异常错误
    MongoDB 介绍
    python virtualenv
    Docker Compose 模板文件 V2
  • 原文地址:https://www.cnblogs.com/Byrd/p/2088814.html
Copyright © 2011-2022 走看看