Home > Web Front-end > JS Tutorial > body text

How to put and get values ​​into cookies in js (graphic tutorial)

亚连
Release: 2018-05-18 15:55:20
Original
2401 people have browsed it

The following is how I put and get values ​​into cookies in js. Interested students can take a look.

First of all, there is a basic concept that needs to be understood, why values ​​are stored in cookies. If yours is a jsp page, then it is not necessary. You can completely use the session object to achieve the stored value you want. Of course, it is not impossible to use cookies.

If it is a mobile development or a simple html page and you want to store a value that is still valid when you open the page next time, you have to use cookies. The front-end js plug-in I use is jquery.cookie.js. This can be downloaded from the Internet, and the most basic usage is also very simple

The first step: introduce js

    <script src="/XX/js/login/jquery-1.5.1.min.js"></script>
     <script src="/XX/js/login/jquery.cookie.js"></script>
Copy after login

The second step: store the value

$.cookie(&#39;the_cookie&#39;, &#39;the_value&#39;, { expires: 7, path: &#39;/&#39; });
一步写到位,不要轻易把path去掉。不然只能在当前js使用,我吃过亏的
举个实例吧:
需求:城市定位,需要下次进入页面时记住上次自动定位的城市名字或者手动选择的城市名字
百度地图API功能
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
               var 城市名= r.address.city;(拿到的城市名字)
        //往cookie里面放城市名称
          $.cookie(&#39;locateCity&#39;, 城市名, { expires: 7 ,path:&#39;/&#39;});
            }
            else {
                //alert(&#39;failed&#39;+this.getStatus());
                mui.alert("城市定位失败");
            }        
        },{enableHighAccuracy: true})
Copy after login

The third step: Value

var locateCity = $.cookie(&#39;locateCity&#39;);
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

javascript implements uploading files to the background for reception

a tag how to call JavaScript

Detailed explanation of the five common functions in JavaScript

The above is the detailed content of How to put and get values ​​into cookies in js (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template