PDA

View Full Version : سوال: ایجاد و ذخیره Cookie



e_a_23
جمعه 08 اردیبهشت 1391, 14:59 عصر
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());
document.cookie=c_name + "=" + c_value;
}


توضیح کد بالا:

The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.

In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

علت نوشتن کد خط 5 چیست؟

mehdi.mousavi
شنبه 09 اردیبهشت 1391, 19:59 عصر
سلام.
فرض کنید value ی ورودی تابع شما "myvalue=2" باشه و cname هم myCookie. در اینصورت، در خط آخر کد، document.cookie میشه:


myCookie=myvalue=2

که ممکنه برخی از برنامه های Server-Side باهاش مشکل داشته باشن و نتونن بر اساس انتظار اونو Parse کنن. بنابراین نویسنده کد، ابتدا value رو escape کرده تا مقدار زیر در document.cookie نوشته بشه:


myCookie=myvalue%3D2

بنظرم بهتره جای escape از encodeURIComponent استفاده بشه...

موفق باشید.