[JavaScript] day 21 (cookie)

cookie

1, Callback function

A function is passed to another function as a parameter, function B is used as a parameter of function a, function B is called inside function a, and function B is called the callback function of function a.

Syntax:
function A(callback){
  callBack()
}
B Is also a function
A(B)

Syntax 1:

    function success(callback){
        callback()
    }

    success(function(){
        console.log(1);
    })
Grammar 2:

    function success(callback){
        callback("Zhang San")
    }

    success(function(data){
        console.log(data);
    })


encapsulation ajax´╝îSend a get request
 Normal version
function ajaxget(){
  let xhr = new XMLHttpRequest();
  xhr.open('get', '05checkUser.php?username=' + this.value);
  xhr.send();
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      console.log(xhr.responseText);
    }
  }
}
ajaxget();
-----------------------------------------------------------------
Callback function version
function ajaxget(callback){
  let xhr = new XMLHttpRequest();
  xhr.open('get', '05checkUser.php?username=' + this.value);
  xhr.send();
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      callback(xhr.responseText);
    }
  }
}

ajaxget(funciton(data){
   console.log(data);        
})

2, ajax encapsulation

Principle of encapsulation:

Before encapsulation, you need to think about what parameters are passed to facilitate encapsulation when users call later. Some users want to call later.

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});


Or:

$.ajax({
   type: "POST",
   url: "some.php",
   data: {name:'Zhang San',age:18},
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
});
function $ajax(options) {
    // 1. Create xhr object XMLHTTPRequset
    let xhr = new XMLHttpRequest();
    let params = formdata(options.data);
    // 2. Set request parameters (divided into get and post)
    if (options.type == 'GET') {
        xhr.open('get', options.url + '?' + params, true);
        xhr.send();
    }
    if (options.type == 'POST') {
        xhr.open('post', options.url);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send(params);
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            options.success(xhr.responseText)
        }
    }
}
// Change the request parameters in object format to username = Zhangsan & password = 12345 format
function formdata(data) {
    let arr = [];
    // Object traversal: for in loop
    for (let k in data) { //
        arr.push(k + '=' + data[k])
    }
    return arr.join('&');//username=zhangsan&password=12345 // arr: [username='zhansgan',password='12233']
}

3, ajax encapsulation case

Baidu search tips case
<?php
 $music = $_GET['music'];
 if ($music=='you') {
      echo '[{"msg":"You are my eye"},{"msg":"You are my little apple"},{"msg":"You are my little pepper"}]';
 }
?>
  otxt.oninput = function () {
        ajaxtools({
            type: "GET",
            url: "music.php",
            data: "music=" + otxt.value,
            success: function (msg) {
                let str = ''
                if (msg) {
                    let arr = JSON.parse(msg);
                    arr.forEach(function (item, index) {
                        str += `<li>${item.msg}</li>`
                    })
                } else {
                    str = ''
                }      
                oul.innerHTML = str;
            }
        })
 }

4, Cookies

Explanation of terms:

1. Session: the process from the beginning of browsing to the end of browsing when users enter the website is called a session

2.http stateless: because the server has no "memory ability". It cannot support "transactional" operations that require multiple consecutive steps.
For example, for e-commerce shopping, first log in, then add a shopping cart, and then place an order, settle and pay. This series of operations need to guide the user's identity, but the "stateless" server does not know that these requests are interrelated.
Cookie technology can solve this problem.

HTTP is an unsaved state.
With the continuous development of the Web, there are more and more cases where business processing becomes difficult due to statelessness. For example, when a user logs in to a shopping website, even after he jumps to other pages of the website, he needs to continue to maintain the login status. In order to master who sent the request, the website needs to save the user's status.
Although HTTP/1.1 is a stateless protocol, in order to achieve the desired state keeping function, Cookie technology is introduced. With cookies and HTTP protocol communication, the state can be managed.

4.1 cookie status management

How to manage the state of cookie s?

The HTTP protocol itself is stateless. What is statelessness? That is, the server cannot judge the user identity.
A Cookie is actually a small piece of text information (key value format).
The client sends a request to the server. If the server needs to record the user status, it uses response to issue a Cookie to the client browser. The client browser will save the Cookie.
When the browser requests the website, the browser submits the requested URL to the server together with the Cookie.
The server checks the Cookie to identify the user status.

The generation process of cookie: open the browser - > enter the web address - > Enter - > domain name resolution - > access the server
- > return to the home page - > store cookie s in the browser
When the user wants to access the secondary page, open a new window and automatically judge the content in the previous page
Whether it contains cookies. If so, bring the cookie data to the next page


What is cookie 2.4?

Session tracking technology

4.3 characteristics of cookies

(1) Cookies are stored in the client browser and information is stored in the user's hard disk, so global variables can not be made.
(2) Cookies are browser related. Cookies saved by different browsers cannot be accessed to each other.
(3) Cookies may be deleted by the user.
(4) Cookies are session level by default.

Session level: that is, when the browser is closed, the cookie will be destroyed immediately, but we can also manually set the expiration time of coolie during storage.

(5) There are restrictions on the number and size of cookie s. The number is about 50 words, and the amount of data stored is 4k. Cookies only support storing string type data.
(6) Path restriction: when storing cookies, you can specify a path. Only the outer layer cookies can be read from the outer layer, but the inner layer cannot be read from the outer layer.

4.4 storage and retrieval of cookie data

document.cookie = "key=value"              storage cookie
document.cookie                        obtain cookie
storage cookie
<body>
  <input type="button" value="Save" id = "s"/>
  <input type="button" value="take" id = "g" />
  <a href="2.html" target="_blank">Jump to secondary page</a>
</body>
 
<script>
    let oSave = document.getElementById("s");
    let oGet = document.getElementById("g");
    //Save cookie s
    oSave.onclick = function(){
        document.cookie = "name=laowang";
        alert("storage cookie success");
    }
    oGet.onclick = function(){
        alert(document.cookie);
    }
</script>

4.5 cookie life cycle

The life cycle is cookie The time the data was saved on the browser
document.cookie = "key=value;expires=Time object"

4.6 encapsulation of cookies

<script>
    //Encapsulate a method to obtain cookie value
    function getCookie(key){
        let str = document.cookie;
        let arr = str.split("; ");//Do not delete the space after the semicolon. The key value pair between cookie s is through semicolon + space
        for(let i=0; i<arr.length; i++){
            let item = arr[i].split("=");
            if(item[0] == key){
                return item[1];
            }
        }
        //There is no cookie, or there is a cookie, but the key is not found. If there is no cookie, an empty string is returned
        return "";
    }
    //Encapsulates a method for setting cookie values
    function setCookie(key,value,day){
        let d = new Date();
        d.setDate(d.getDate()+day);
        document.cookie = key+"="+value+";expires=" + d;
    }
    
    //delete cookie 
    function delCookie(key){
        setCookie(key," ",-1);
    }
    

</script>

Keywords: Javascript Front-end

Added by bongbong on Fri, 25 Feb 2022 11:59:59 +0200