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