2012年7月27日 星期五

Why jQuery Cookie use encodeURIComponent/decodeURIComponent?

因為用JS存Cookie的時候有夾帶中文的內容,發現PHP印出來會變成亂碼,所以自己做了測試後得到結論JS這邊用 encodeURIComponent/decodeURIComponent 方法來編解碼字串內容就OK了,用JS or PHP存取Cookie都不會有問題。


原本從W3C參考來的setCookie method:是用escape編解碼要儲存的cookie內容。


function setCookie(c_name,value,exdays)  
{  
var exdate=new Date();  
exdate.setDate(exdate.getDate() + exdays);  
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()+"; path=/project/");  
document.cookie = c_name + "=" + c_value;  
}


但是用此方式,用PHP想取得輸出Cookie內容時候;setCookie("hello","你好",30) -->JS存一個屬性hello 值為"你好"的cookie內容

echo $_COOKIE['hello'];  



你會得到的是編碼後的Unicode 字符:%u4F60%u597D ,而不是"你好"。
所以我在原本JS這邊存取Cookie的編解碼改用encodeURIComponent/decodeURIComponent去處理要存取的Cookie內容:


function encode_setCookie(c_name,value,exdays)
{
var exdate=new Date();  exdate.setDate(exdate.getDate() + exdays); 
//use encodeURIComponent encode string and decodeURIComponent decode it.

var c_value=encodeURIComponent(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()+"; path=/project/"); document.cookie = c_name + "=" + c_value; }

我發現PHP的setCookie method似乎也是用同種原理去編碼Cookie內容,
所以這樣一來無論你是用JS存PHP取或者用PHP存JS取"似乎"就不會有通用字符編解碼的問題存在,輸出解碼就很正常。


當然,這也是jQuery Cookie Plugin 採用的方式。

沒有留言:

張貼留言