2016-02-25 33 views
0

我想使用cookie記住數組中的所有值,但不知道如何。我也使用js-cookies。使用cookie記住數組中的所有值 - javascript

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); 
+0

要保存的Cookie使用'Cookies.set( '用戶',JSON.stringify(用戶名));'和加載使用'用戶名= JSON.parse(Cookies.get( '用戶'));' – jcubic

+3

爲什麼選擇cookies?它們不必要地誇大HTTP請求和響應的大小。請查看[網絡存儲](http://www.w3.org/TR/webstorage/),它幾乎得到了普遍支持(並且在沒有lib的情況下易於使用)。 –

+0

@charlietfl他說他使用js-cookies。 – jcubic

回答

0

如前所述,localStorage是一個更好的地方來存儲這些數據,但使用的cookies遵循相同的步驟,只需要得到一個set/get method for Cookies。首先你需要看看是否有價值。如果有,你需要解析它。更新數組後,您需要將該值轉換爲字符串並將其存儲。

//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());