הנך נמצא: מדריך מתקדם / שיעור 2 / דף 11
 


המדריך של תאו ל- JavaScript
 


דפים בשיעור זה:
1: המדריך המתקדם
2: טיפול מיוחד במחרוזות
3: substring
4: מתודת split
5: מערכים אסוציאטיבים
6: דוג' למערך אסוציאטיבי
7: cookies – היכרות
8: עוד אודות cookies
9: קריאת cookies - א'
10: קריאת cookies - ב'
11: קריאה וכתיבה
12: עוד אודות cookies
13: cookie - path/domain
14: סיכום שיעור 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

שיעור 2

דף 11: קריאה וכתיבה של מספר cookies במקביל.

בדף האחרון למדנו כיצד לשמור מידע רב ב- cookie אחת. דרך נוספת לעשות זאת, היא ע"י שימוש במספר cookies.

שמירת מספר cookies היא מאוד ברורה. למדנו שלכל cookie יש שם. בדוגמא האחרונה, קראנו ל- cookie שלנו בשם: my_happy_cookie, ובצענו משהו כזה:

var the_cookie = "my_happy_cookie=happiness_and_joy";
document.cookie = the_cookie;

על מנת לשמור מספר cookies, פשוט תעניק שם שונה לכל cookie. אם אתה שומר עוגייה חדשה, קביעת document.cookie אינה מוחקת את cookies שכבר שם. כך שאם תעשה זאת כך:

var the_cookie = "my_happy_cookie=happiness_and_joy";
document.cookie = the_cookie;
var another_cookie = "my_other_cookie=more_joy_more_happiness";
document.cookie = another_cookie;

עכשיו יש לך הגישה לשתי העוגיות. זה קצת מוזר, אז וודא שאתה מבין בדיוק מה קרה.

הבא נניח שאתה מבצע את בלוק הקוד האחרון, וברצונך לגשת אל my_happy_cookie. אם תביא ב- document.cookie אתה תראה:

my_happy_cookie=happiness_and_joy;
my_other_cookie=more_joy_more_happiness;

אם אתה לא מאמין לי פשוט הבט ב- cookie.

זה מאוד נחמד, אולם קריאת cookie ספציפית הופכת קצת יותר מסובכת. הנה קוד שמאפשר לבודד cookie ספציפית. הקוד נלקח מספריית ה- cookies של webmonkey.

function WM_readCookie(name)
{
  // if there's no cookie, return false else get the value and return it
  if(document.cookie == '')
    return false;
  else
    return
  unescape(WM_getCookieValue(name));
}

function WM_getCookieValue(name)
{
  // Declare variables.
  var firstChar, lastChar;
  
  // Get the entire cookie string.
  // (This may have other name=value pairs in it.)
  var theBigCookie = document.cookie;
  
  // Grab just this cookie from theBigCookie string.
  // Find the start of 'name'.
  firstChar = theBigCookie.indexOf(name);
  
  // If you found it,
  if(firstChar != -1)
  {
    // skip 'name' and '='.
    firstChar += name.length + 1;
    
    // Find the end of the value string (i.e. the next ';').
    lastChar = theBigCookie.indexOf(';', firstChar);
    if(lastChar == -1) lastChar = theBigCookie.length;
    
    // Return the value.
    return theBigCookie.substring(firstChar, lastChar);
  } else {
    // If there was no cookie, return false.
    return false;
  }
}

מכייון שהקוד בעל הערות / הארות רבות, אני אתן לך להתמודד איתו לבדך (נו בחייך, אתה יודע את כל אשר נדרש על מנת להבין את הקוד).

ברגע שסיימת לנתח ולהבין כל תו בקוד, בוא נעזוב את החלק הנודע קביעת וקריאת cookies בסיסיות, ונעבור לדיון המעניין אודות הדברים הבאמת מעניינים אותם ניתן לבצע באמצעות cookies.

חזור לתחילת הדף

לדף הבא «--

 
       
       
   
 
 

עמוד ראשי
מדריך בסיסי
מדריך מתקדם
החלפת תמונות
גניבת קוד
מפת האתר