我想出了一个基于客户端的解决方案,它使用jstorage来存储会话数据。您还需要json2库,因为jstorage需要它。
像这样的解决方案确实没有安全性,所以不要用它来试图阻止访问任何敏感的东西等。
这是每个页面的 head .. /head 部分中的代码:
<!-- load the css used by the jquery-mobile library -->
<link rel="stylesheet" href="jquery.mobile-1.3.1.min.css" />
<!-- load the json2 library (required for jstorage use) -->
<script src="json2.js"></script>
<!-- load the jquery library -->
<script src="jquery-1.9.1.min.js"></script>
<!-- load the jstorage library -->
<script src="jstorage.js"></script>
<!-- load the js that binds to various jqm events here, BEFORE loading jqm -->
<script src="example_client_session.js"></script>
<!-- load the jquery-mobile (jqm) library -->
<script src="jquery.mobile-1.3.1.min.js"></script>
“example_client_session.js”文件包含以下内容:
$(document).on("pageinit", function(event) {
var session = $.jStorage.get('session', ''); // syntax: $.jStorage.get(keyname, "default value")
// See: https://github.com/jquery/jquery-mobile/issues/3384
var activePage = $(event.target);
// if the current page is not the login_page *and* there is no session *then* redirect to the login_page
if(activePage[0].id != 'login_page' && (!session) ){
$.mobile.changePage("#login_page");
}
// if the current page *is* the login_page *and* there is already a session *then* redirect to landing page
if(activePage[0].id == 'login_page' && session ){
$.mobile.changePage("whatever_landing_page.htm");
}
});
$(document).on("pageinit", "#login_page", function() {
console.log('pageinit event - login_page only');
$('#login_button').on('click', function(e){
console.log('click event for login_button');
e.preventDefault();
// .. do whatever validation here
if($('#name').val()){
// .. if good to go, create the session
$.jStorage.set('session', $('#name').val(), {TTL: 28800000});
// syntax: $.jStorage.set('keyname', 'keyvalue', {TTL: milliseconds}); // {TTL... is optional time, in milliseconds, until key/value pair expires}
// redirect to whatever page you need after a successful 'login'
$.mobile.changePage("whatever_landing_page.htm");
}else{
$('#login_message').html('<strong>Please provide a name before proceeding</strong>');
}
});
});
最后,login_page 如下所示:
<div data-role="page" id="login_page" data-theme="b" data-content-theme="b">
<div data-role="header">Header Content</div>
<div data-role="content">
Please Login
<div id="login_message"></div>
<form name="login_form" id="login_form">
<div data-role="fieldcontain">
<label for="name">Name:</label> <input type="text" name="name" id="name" value="" />
</div>
<input type="submit" id="login_button" name="login_button" value="Login" />
</form>
</div>
<div data-role="footer">Footer Content</div>
</div>