跨域讀取Cookies(續)

前面咱們說的跨域讀取Cookie,僅限於同一級域名狀況。javascript

要跨域讀取或設置Cookie,這種方法還有侷限,咱們能夠用下面的方法來簡單實現。java

<script type="text/javascript">
    function createScript(theme){
        var url = "http://xxx.xx.xx.xx/gzgx/themeStyle.jsp?theme="+theme;
        var script = document.createElement('script');
        script.id="remoteScriptLinkStyle";
        script.setAttribute('src', url);
        // 把script標籤加入head,此時調用開始  
        document.getElementsByTagName('head')[0].appendChild(script); 
    }
    function setRomteCookie(theme){
        if(Ext.DomQuery.selectNode("script[id='remoteScriptLinkStyle']")==null){
            createScript(theme);
        }else{
            Ext.DomQuery.selectNode("script[id='remoteScriptLinkStyle']").remove();
            createScript(theme);
        }
    }
</script>

調用方法:跨域

            setRomteCookie(subCook);

在遠程服務器端寫一個處理themeStyle.jsp便可:服務器

<%
    String theme = request.getParameter("theme");
    System.out.println("theme:"+theme);
    Cookie[] cookies = request.getCookies();
    if(cookies != null && cookies.length > 0){
        for(int i=0;i<cookies.length;i++){
            Cookie cookie = cookies[i];
            if("theme".equals(cookie.getName())){
                response.addCookie(cookie);
            }
        }
    }
    Cookie cookie = new Cookie("theme",theme);
    response.addCookie(cookie);
%>

這樣就可以本地請求遠程設置Cookie了。cookie

相關文章
相關標籤/搜索