javascript - JQuery Mobile 和 Cordova 页面模板

标签 javascript json jquery-mobile cordova

我的任务是为我们的中型学校董事会创建一个移动应用程序来宣传我们的学校。最初,这看起来很简单——我捕获了 Cordova 和 Eclipse,将 jQuery Mobile 库扔进去并为我的第一所学校设置了几个页面(我认为总共 5 个)。复制/粘贴/编辑内容/更新其他 17 个的链接。

然后我的老板说“用每所学校的颜色制作页面”。再次,简单易行。几节 CSS 类(class)之后,所有大约一百页都很漂亮并且与学校相匹配。

然后是重磅炸弹。到目前为止,所有数据都是本地的 - .htm 文件,这些文件将与应用程序一起安装,并在用户单击它们时由应用程序加载:不需要数据连接。今天早上,有人问我是否可以在不更新应用程序的情况下即时更改信息。我,愚蠢但诚实地说“不”- 你可以猜到下一个请求是什么。

因此,我需要一种方法来完成此任务。我现在的想法是在服务器端运行一些接收某种 ID 号 (appdata.schoolbord.web/123) 的东西,它会返回一个包含数据的 JSON 对象——可能是一个标题,一个名字页面模板(这样我就可以将我的 93 页减少到只有几页)、一些 CSS(只是为了停止下一个请求)然后将数据滑入模板。

有没有使用 Cordova 和 jQuery Mobile 的简单方法来做到这一点?任何方向的指针都会很棒。谢谢。

最佳答案

这是一个简单的例子。我创建了一个 jQM 登录页面,您需要输入您的用户名和密码。此数据将用于检查数据库中是否存在用户名,如果存在则返回 true,否则返回 false。 我建议您创建一个更好的数据库读取逻辑,这是一个简单的解决方案,容易出现 SQL 注入(inject),但它会很好地完成您的作业。

index.php :

<!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.2.0/jquery.mobile-1.2.0.min.css" />
    <style>
        #login-button {
            margin-top: 30px;
        }        
    </style>
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script src="js/custom.js"></script>
</head>
<body>
    <div data-role="page" id="login">
        <div data-theme="a" data-role="header">
            <h3>Login Page</h3>
        </div>

        <div data-role="content">
            <label for="username">Enter your username:</label>
            <input type="text" value="" name="username" id="username"/>
            <label for="password">Enter your password:</label>
            <input type="password" value="" name="password" id="password"/>  
            <a data-role="button" id="login-button" data-theme="b">Login</a>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3></h3>
        </div>

        <div data-role="content">
            Here goes content
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">
            <h3>Page footer</h3>
        </div>
    </div>    
</body>
</html>

json.php :

<?php
    $var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
    $jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object

    $username = $jsonObject->{'username'}; // Get username from object
    $password = $jsonObject->{'password'}; // Get password from object

    mysql_connect("localhost","root","");  // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
    @mysql_select_db("test") or die( "Unable to select database"); // Connect to database called test

    $query = "SELECT * FROM users WHERE user_name = '".$username."' and user_pass = '".$password."'";
    $result=mysql_query($query);
    $num = mysql_numrows($result);

    if($num != 0) {
        echo "true";
    } else {
        echo "false";        
    }
?>

自定义.js :

$(document).on('pagebeforeshow', '#login', function(){ 
    $('#login-button').on('click', function(){
        if($('#username').val().length > 0 && $('#password').val().length > 0){
            userObject.username = $('#username').val(); // Put username into the object
            userObject.password = $('#password').val(); // Put password into the object
            // Convert an userObject to a JSON string representation
            var outputJSON = JSON.stringify(userObject);
            // Send data to server through ajax call
            // action is functionality we want to call and outputJSON is our data
            ajax.sendRequest({action : 'login', outputJSON : outputJSON});
        } else {
            alert('Please fill all nececery fields');
        }
    });    
});

$(document).on('pagebeforeshow', '#index', function(){ 
    if(userObject.username.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
        $.mobile.changePage( "#login", { transition: "slide"} ); // In case result is true change page to Index  
    }
    $(this).find('[data-role="header"] h3').append('Wellcome ' + userObject.username); // Change header with wellcome msg
    //$("#index").trigger('pagecreate');
});

// This will be an ajax function set
var ajax = {
    sendRequest:function(save_data){
        $.ajax({url: 'http://localhost/JSONP_Tutorial/json.php',
            data: save_data,
            async: true,
            beforeSend: function() {
                // This callback function will trigger before data is sent
                $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
            },
            complete: function() {
                // This callback function will trigger on data sent/received complete
                $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
            },
            success: function (result) {
                if(result == "true") {
                    $.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
                } else {
                    alert('Login unsuccessful, please try again!'); // In case result is false throw an error
                }
                // This callback function will trigger on successful action
            },
            error: function (request,error) {
                // This callback function will trigger on unsuccessful action                
                alert('Network error has occurred please try again!');
            }
        });
    }
}

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
    username : "",
    password : ""
}

如果需要,请通过我的电子邮件与我联系(您可以在 ma profile 中找到它),我将向您发送带有源代码和使用的 sql 脚本的项目。

关于javascript - JQuery Mobile 和 Cordova 页面模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14690590/

相关文章:

c++ - 在 C++ 中读取 json 文件

python - 将 pandas multiindex 系列转换为 Json python

ruby-on-rails - 为什么我的 ajax-loader.gif 出现路由错误?

javascript - 如何缓存图标javascript

javascript - 如何使用 js setinterval() 在两种背景颜色之间切换

c# - JSON 序列化器 - 当前端缺少设置为 false 的 bool 值时

jquery 移动导航栏和 ListView 项目有时会出现圆角

javascript - URL 自动附加到页面 URL

javascript - 如何在 Windows 上运行 Node 集群?

asp.net - 将 runat ="server"添加到控件时,JQuery Mobile 会丢失样式