使用cookies-javascript记住数组中的所有值
我希望能够使用cookies记住数组中的所有值,但不知道如何记住。我也在使用js cookies使用cookies-javascript记住数组中的所有值,javascript,jquery,html,cookies,Javascript,Jquery,Html,Cookies,我希望能够使用cookies记住数组中的所有值,但不知道如何记住。我也在使用js cookies Here is my code: var usernames = new Array(); var input = $('#input').val(); usernames.push(input); // each time something is inputted, it'll be saved to the // array usernames. I want it so that
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
如前所述,是存储这些数据的更好的地方,但是使用cookie遵循相同的步骤,只需要获得一个。首先,您需要查看是否存在值。如果有,您需要解析它。更新数组后,需要将值转换为字符串并存储
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());
要保存cookies,请使用
cookies.set('users',JSON.stringify(usernames))要加载,请使用usernames=JSON.parse(Cookies.get('users'))代码>为什么是cookies?它们不必要地扩大了HTTP请求和响应的大小。相反,请看一看,它几乎得到了普遍支持(并且在没有lib的情况下易于使用)。@charlietfl他说他使用js cookies。@jcubic my bad…错过了这一点