ב Asp.net מאוד נוח לעבוד על עוגיות, לקבץ נתונים לעוגייה אחת. ב Javascript הסיפור קצת אחר, השפה אינה כוללת אופציה של קיבוץ נתונים לעוגייה אחת. דבר זה “מכריח” אותנו ליצור עוגיות לכל נתון. במאמר זה אציג לכם דרך לדמות את שיטת העבודה עם עוגיות ב JavaScript בדומה ל Net. |  |
לעבודה!
ב Net. זאת הדרך ליצירת עוגיות:
HttpCookie c = new HttpCookie(".netCookie");
c["key1"] = "value1";
c["key2"] = "value2";
Response.Cookies.Add(c);
לאחר שנריץ את העמוד ונבדוק את העוגייה נקבל את:

על מנת לקבל את את העוגיות כל מה שנצטרך לכתוב הוא:
HttpCookie gc = Request.Cookies[".netCookie"];
if (gc != null)
Response.Write(gc["key1"]);
ב JavaScript הסיפור קצת אחר
JavaScript אינו מאפשר לעבוד על קבוצה של נתונים בתוך עוגייה. הפתרון הבא יאפשר לכם לעשות זאת.
יצרתי אובייקט אשר מנהל את העוגיות (יצרה של העוגיות נלקחה מאתר הזה):
var cookies = {
set: function (name, value, days) {
/// <summary>Set Cookie</summary>
/// <param name="name" type="string">Cookie Name</param>
/// <param name="value">Cookie Value</param>
/// <param name="days" type="int">Cookie live (in days)</param>
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
},
get: function (name) {
/// <summary>Get Cookie</summary>
/// <param name="name" type="string">Cookie Name</param>
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function (name) {
/// <summary>Remove Cookie</summary>
/// <param name="name" type="string">Cookie Name</param>
this.set(name, "", -1);
}
};
השימוש בזה הוא ממש פשוט:
//set cookie
cookies.set("cookieName","cookieValue", 10)
//get cookie
cookies.get("cookieName")
//remove cookie
cookies.remove("cookieName")
עכשיו לחלק המתקדם יותר
נגיד ושמרתי בעוגייה אחת את המידע הבא:
key1=value1&value11&key2=value2
הערך של “key1” הוא “value1&value11” (לא נוכל לפצל לפי “&”)
ה Prototype הבא יאפשר לכם לפצל את המחרוזת לאובייקט של נתונים:
String.prototype.toNameCollection = function () {
/// <summary>Convert string collection to object list</summary>
var arr = this.split("="),
coll = {},
_tempVal;
//no data was found
if (arr.length < 2)
return null;
//only one key
else if (arr.length === 2) {
coll[arr[0]] = arr[1];
console.log(coll);
return coll;
}
//multy keys
for (var i = 0; i < arr.length; i++) {
//first value always a key
if (i === 0) {
_tempVal = arr[i + 1];
//get value (from last & is a new key)
coll[arr[i]] = _tempVal.substring(0, _tempVal.lastIndexOf("&"));
} else if (i === (arr.length - 1)) {
//check last item (last item is always a value)
coll[arr[i - 1].substring(arr[i - 1].lastIndexOf("&") + 1, arr[i - 1].legnth)] = arr[i];
}
else {
_tempVal = arr[i + 1];
if (_tempVal) {
coll[arr[i].substring(arr[i].lastIndexOf("&") + 1, arr[i].legnth)] = _tempVal.substring(0, _tempVal.lastIndexOf("&"));
}
}
}
return coll;
};
הקוד הנ”ל יודע לפצל ולזהות את הערכים ושמות של האובייקטים גם כאשר “&” הוא חלק מה Value.
ועל מנת לסגור את כל הסיפור ישנה פונקציה אשר מחפשת את ה Value באובייקט:
function GetValueFromKey(key, collection) {
/// <summary>Get value from collection</summary>
/// <param name="key">key in collection</param>
/// <param name="collection" type="object">Object Collection</param>
if (typeof (collection) !== 'object')
return null;
for (var j in collection) {
if (collection.hasOwnProperty && collection.hasOwnProperty(j))
if (key === j)
return collection[j];
}
return null;
};
ולשימוש:
var s = "key1=value1&value11&key2=value2"
o = s.toNameCollection();
var key1Value = GetValueFromKey("key1", o);
הערה חשובה:
אם ה Value של ה Cookie כולל סימן “=” הסקריפט לא יעבור תקין.
על מנת לפתור את הבעיה יש לקודד את ה Value:
encodeURIComponent(Value)
אשמח לקבל הצעת לשיפור ולייעול :)