localStorage の最後のオブジェクト (「name」属性と「email」属性を持つユーザー) を取得しようとしています。「name」と「email」の値に個別にアクセスし、それらを文字列として出力したいと思います。これは私のテンプレートが出力するものです:
{"name":"eamon","email":"eamon.white@yahoo.com"}
出力したい:
eamon, eamon.white@yahoo.com
これが私のコードです:
templates/usershow.ejs
<ul>
<li><%= localStorage.getItem(localStorage.key(localStorage.length - 1)) %></li>
</ul>
アプリケーション.js
$(document).ready(function() {
$("#signupform").submit(function(e) {
e.preventDefault();
var user = {
name: $('#pname').val(),
email: $('#email').val()
};
localStorage.setItem('user', JSON.stringify(user));
//console.log(JSON.parse(localStorage.getItem('user')));
var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
var content = document.getElementById('content');
content.innerHTML = content.innerHTML + html;
$("#signupform").remove();
});
});
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>it IT</title>
<link rel="stylesheet" type="text/css" href="application.css" />
<script src="jquery.js"></script>
<script src="application.js"></script>
<script type="text/javascript" src="ejs_production.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>it IT</h1>
<div id="signup">
<form id="signupform">
Name: <input type="text" name="pname" id="pname"><br>
Email: <input type="text" name="email" id="email"><br>
<input type="submit" value="sign up">
</form>
</div>
<div id="signin"></div>
<div id="content"><h2>Name : Email</h2></div>
</body>
</html>
アップデート
テンプレートを次のように変更しました。
<ul>
<li><%= localStorage.getItem(localStorage.key(localStorage.length - 1)).name %></li>
</ul>
空の文字列を返しているように見えますが、レンダリングされたページのリストの箇条書きの横には何もありません。基本的にユーザーデータベースを作成しようとしています...これはそれについての方法ですか?
また、次のエラーが表示されます。
XMLHttpRequest cannot load file://localhost/Users/Eamon/code/templates/usershow.ejs. Cross origin requests are only supported for HTTP. ejs_production.js:1
Uncaught #<Object> ejs_production.js:1
クロムコンソールで...そして何もレンダリングされません...しかし、すべてがFirefoxで動作するようです...
アップデート
これにより、ロードファイルエラーが解消されました。
var html = new EJS({url: 'http://localhost/code/templates/usershow.ejs'}).render(user);
それは正しい解決策ですか?私はまだUncaught #<Object> ejs_production.js:1
エラーが発生しています。