Session Storage in js

前端 未结 3 1015
死守一世寂寞
死守一世寂寞 2021-02-14 18:06

Hi i\'m a beginner in JavaScript i would like to ask if its possible to session the data i\'m getting from a server. The data i want to session is the \'data.xhr.response\' i se

相关标签:
3条回答
  • 2021-02-14 18:49

    Session storage is same as local storage but the only difference is that data stored in session storage will clear automatically once page session will expire.

    Now come to your question. In your success function, do like below to store data:

    success : function(data) {
        console.log(data.xhr.response);
        sessionStorage.setItem('dataStored', data.xhr.response);
    
    }
    

    Usage is like below:

    // Save data to sessionStorage
    sessionStorage.setItem('dataStored', data.xhr.response);
    
    // Get saved data from sessionStorage
    var data = sessionStorage.getItem('dataStored');
    
    // Remove saved data from sessionStorage
    sessionStorage.removeItem('dataStored');
    
    // Remove all saved data from sessionStorage
    sessionStorage.clear();
    

    For more information about sessionStorage check this link : https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

    0 讨论(0)
  • 2021-02-14 18:51

    Try reading this article about session storage on mozilla.org, it shows how straightforward it is. In your case it should be as simple as:

    $('#file-upload').dropzone({
      maxFiles: 1,
      acceptedFiles: ".pdf,.doc,.docx,.html", 
      dataType: "json",
      success : function(data) {
          sessionStorage.setItem('xhr', data.xhr.response);
      }
    });
    
    0 讨论(0)
  • 2021-02-14 18:54

    In your case you can either to choose sessionStorage or localStorage. Both can save the data response for you in the browser. The difference is only the expiry that localStorage wont expire while sessionStorage stores data for one session (data is lost when the browser tab is closed).

    So the steps are:

    1. Check your browser to see if it supports webStorage:

      if (typeof(Storage) !== "undefined") {
          // Code for localStorage/sessionStorage.
      } else {
          // Sorry! No Web Storage support..
      }
      
    2. Implement localStorage:

      localStorage.setItem("lastname", "Smith");  // save data
      var user = localStorage.getItem("lastname"); // get data
      localStorage.removeItem("lastname");  // remove data
      
    3. Implement sessionStorage:

      sessionStorage.setItem('lastname', 'Smith'); // save data
      var user = sessionStorage.getItem('lastname'); // get data
      sessionStorage.removeItem('dataStored');  // remove data
      

    Hope it helps!

    0 讨论(0)
提交回复
热议问题