Skip to content

Instantly share code, notes, and snippets.

@kazua
Last active December 21, 2015 08:58
Show Gist options
  • Save kazua/6281353 to your computer and use it in GitHub Desktop.
Save kazua/6281353 to your computer and use it in GitHub Desktop.
JSON読み込みとwebstorageの読み書きのお試し
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
//write kazua
var json = '{"record": ['
+ '{"name": "Yusuke Sasaki", "score": {"japanese" : 74, "english" : 65}},'
+ '{"name": "Kazuki Tajima", "score": {"japanese" : 61, "english" : 87}},'
+ '{"name": "Minako Ogawa", "score": {"japanese" : 45, "english" : 91}},'
+ '{"name": "Toru Nagase", "score": {"japanese" : 85, "english" : 97}}'
+ ']}';
function jsontest() {
if(typeof(JSON)==='undefined'){
alert("JSON.parseは使用できません。");
obj = eval("(" + json + ")");
}else{
obj = JSON.parse(json);
}
for(i =0; i<obj.record.length; i++){
document.getElementById("savetext").value += "名前:" + obj.record[i].name + "\n" + " 国語:" + obj.record[i].score.japanese + "\n" + " 英語:" + obj.record[i].score.english + "\n";
}
}
function savewebstorage(){
if (window.localStorage)
window.localStorage.setItem("stg",document.getElementById("savetext").value);
}
function readwebstorage(){
if (window.localStorage)
document.getElementById("readtext").value = window.localStorage.getItem("stg");
}
</script>
</head>
<body>
<input type="button" id="json" onclick="jsontest();" value="JSON読取">
<br />
<input type="button" id="savedata" onclick="savewebstorage();"
value="webstorageに保存">
<br />
<textarea id="savetext" rows="10" cols="30"></textarea>
<br />
<input type="button" id="readdata" onclick="readwebstorage();"
value="webstorageを読取">
<br />
<textarea id="readtext" rows="10" cols="30"></textarea>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment