Я удивлен, что кто-то все еще использует jQuery Mobile, но я думаю, что у меня есть большая часть кода, который вам нужен.
Несколько лет назад я написал статью, посвященную сложному руководству по авторизации jQuery Mobile: https://www.gajotres.net/complex-jquery-mobile-authorization-example/
Основная идея состоит в том, чтобы опубликовать информацию об авторизации от клиента jQM:
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).on("mobileinit", function () {
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<a href="#login" class="ui-btn-left ui-btn ui-btn-inline ui-mini ui-corner-all ui-btn-icon-left ui-icon-delete" id="back-btn">Back</a>
<h3>Welcome Page</h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
Переслать эту информацию на серверную часть PHP.Конечно, вам нужно будет обрабатывать чтение / запись БД;В моем примере используется какой-то ORM, например, Propel, так как он содержит большое количество доступных учебных пособий.
<?php
function authorize()
{
//normally this info would be pulled from a database.
//build JSON array
$status = array("status" => "success");
return $status;
}
$possible_params = array("authorization", "test");
$value = "An error has occurred";
if (isset($_POST["action"]) && in_array($_POST["action"], $possible_params))
{
switch ($_POST["action"])
{
case "authorization":
$value = authorize();
break;
}
}
//return JSON array
exit(json_encode($value));
?>
Получите ответ обратно на jQuery Mobile и, в зависимости от типа страницы, откройте соответствующую страницу, используя:
$.mobile.changePage("#second");
Вот целый пример jQM из моего урока:
var userHandler = {
username : '',
status : ''
}
$(document).on('pagecontainershow', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'login') {
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
userHandler.username = $('#username').val();
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'auth.php',
data: {action : 'authorization', formData : $('#check-user').serialize()},
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show Ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide Ajax spinner
},
success: function (result) {
// Check if authorization process was successful
if(result.status == 'success') {
userHandler.status = result.status;
$.mobile.changePage("#second");
} else {
alert('Logon unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
} else if(activePage.attr('id') === 'second') {
activePage.find('.ui-content').text('Wellcome ' + userHandler.username);
}
});
$(document).on('pagecontainerbeforechange', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'second') {
var to = ui.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#login' && userHandler.status === 'success') {
alert('You cant open a login page while youre still logged on!');
e.preventDefault();
e.stopPropagation();
// remove active status on a button if a transition was triggered with a button
$('#back-btn').removeClass('ui-btn-active ui-shadow').css({'box-shadow':'0 0 0 #3388CC'});
}
}
}
});
Выше урок написан на jQuery Mobile 1.4.5.Хотя уже существует версия 1.5, она все еще является альфа-версией, и есть большая вероятность, что мы никогда не увидим версию 1.5 для RC, поэтому придерживайтесь 1.4.5.
Опять же, вам нужно только написать реализацию обработки БД PHPи это не должно занять у вас много времени, если вы будете придерживаться Propel ORM.