■ Storage 인터페이스를 사용해 로컬 저장소에서 JSON 데이터를 처리하는 방법을 보여준다.
▶ test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script language="javascript"> function onLoad() { var array = JSON.parse(localStorage.getItem('phonebook')); if(array == null) { localStorage.setItem('phonebook', JSON.stringify(new Array)); } showData(); } function showData() { var message = ''; var array = JSON.parse(localStorage.getItem('phonebook')); for(var i = 0; i < array.length; i++) { message = message + array[i].name + ', ' + array[i].phone + ', ' + '<a href="javascript:removeData(' + i + ');">삭제</a><br />'; } document.getElementById('output').innerHTML = message; } function AddData() { var value1; var value2; var array = JSON.parse(localStorage.getItem('phonebook')); value1 = document.getElementById('name').value; value2 = document.getElementById('phone').value; array[array.length] = { name : value1, phone : value2 }; localStorage.setItem('phonebook', JSON.stringify(array)); showData(); document.getElementById('name').value = ''; document.getElementById('phone').value = ''; } function removeData(i) { var array = JSON.parse(localStorage.getItem('phonebook')); array.splice(i, 1); localStorage.setItem('phonebook', JSON.stringify(array)); showData(); } function clearData() { localStorage.removeItem('phonebook'); localStorage.setItem('phonebook', JSON.stringify(new Array)); showData(); } </script> </head> <body onload="onLoad();"> <div id="output">로컬 저장소 JSON 데이터 테스트입니다.</div> <p /> <input id="name" type="text" size="8" /> <input id="phone" type="text" size="12" /> <p /> <input type="button" value="데이터 추가" onclick="AddData();" /> <input type="button" value="데이터 삭제" onclick="clearData();" /> </body> </html> |