Phonegap保存HTML表单数据的txt文件

Posted

技术标签:

【中文标题】Phonegap保存HTML表单数据的txt文件【英文标题】:Phonegap save txt file of HTML form data 【发布时间】:2015-07-30 19:42:37 【问题描述】:

我需要使用 Phonegap 创建一个 ios 应用程序来保存 html 表单。但是,我对 iOS 或 Phonegap 并不太熟悉。谁能指出我正确的方向?

这是我的 HTML:

<!DOCTYPE html>
<html class="ipad" lang="en">
    <head>
        <meta charset="utf-8">
        <title>Hall Render - Resources Sign Up</title>
        <!-- Mobile Viewport -->
            <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <!-- Main Stylesheet -->
            <link href="assets/css/screen.css" media="all" rel="stylesheet" type="text/css">
        <!-- jQuery -->
            <script src="assets/js/jquery-1.11.3-min.js"></script>
        <!-- jQuery Plugins -->
            <script src="assets/js/jquery-validation-1.14.0-min.js"></script>
        <!-- Phonegap JS -->
            <script src="assets/js/phonegap.js"></script>
            <script src="assets/js/cordova.js"></script>
        <!-- Functions -->
            <script src="assets/js/functions.js"></script>
    </head>

    <body onload="onDeviceReady()">
        <!-- Begin Header -->
            <header>
                <div class="wrap">
                    <img src="assets/img/hall_render-logo.png"  >
                    <h1><strong>Health Law</strong> is our business.</h1>
                </div>
            </header>
        <!-- End Header -->
        <!-- Begin Secondary Header -->
            <section id="secondary-header">
                <div class="wrap">
                    <div class="inner-wrap">
                        <h2><strong>Hall Render Alerts Provide</strong> up-to-date information</h2>
                        <p>on topics ranging from general health law to health care reform, HIPAA,<br>
                            employment law, health information technology and health care tax news.</p>
                    </div>
                </div>
            </section>
        <!-- End Secondary Header -->
        <!-- Begin Main -->
            <section id="main">
                <div class="wrap">
                    <div class="inner-wrap">
                        <div class="text">
                            <h3>Sign Up to Receive Hall Render Resources</h3>
                            <p>
                                We appreciate your interest in our firm. As the nation’s largest law firm focused exclusively on matters specific to health care, our knowledge and experience allow us the opportunity to share the latest and most relevant health care news and practical takeaways directly with you. In an evolving industry such as health care, it’s crucial to stay up to date and informed. These email alerts are designed to help you do just that.
                            </p>
                        </div>
                        <form id="signup-form" method="get" action="">
                            <fieldset>
                                <div class="label-input-wrap">
                                    <label for="cfirst-name">First Name: (required)</label>
                                    <input type="text" id="cfirst-name" name="firstname" tabindex="1">
                                </div>
                                <div class="label-input-wrap">
                                    <label for="clast-name">Last Name: (required)</label>
                                    <input type="text" id="clast-name" name="lastname" tabindex="2">
                                </div>
                                <div class="label-input-wrap">
                                    <label for="corganization">Organization:</label>
                                    <input type="text" id="corganization" name="organization" tabindex="3">
                                </div>
                                <div class="label-input-wrap">
                                    <label for="ctitle">Title:</label>
                                    <input type="text" id="ctitle" name="title" tabindex="4">
                                </div>
                                <div class="label-input-wrap">
                                    <label for="cemail">Email: (required)</label>
                                    <input type="email" id="cemail" name="email" tabindex="5">
                                </div>
                                <input id="form-submit" type="submit" value="Sign Up" tabindex="6">
                            </fieldset>
                        </form>
                    </div>
                </div>
            </section>
        <!-- End Main -->
        <!-- Begin Secondary -->
            <section id="secondary">
                <div class="wrap">
                    <div class="inner-wrap">
                        <div class="text">
                            <h3>Thank You</h3>
                            <p>
                                Thank you for signing up to receive Hall Render resources.<br>
                                You will be receiving an email from us soon with the latest health law news.
                            </p>
                        </div>
                    </div>
                </div>
            </section>
        <!-- End Secondary -->
        <!-- Begin Footer -->
            <footer>
                <div id="red-tab"></div>
                <div class="clear"></div>
                <div id="red-banner"></div>
                <div id="footer-hold">
                    <div class="wrap">
                        <p>
                            DENVER <span>|</span> DETROIT <span>|</span> INDIANAPOLIS <span>|</span> LOUISVILLE <span>|</span> MILWAUKEE <span>|</span> PHILADELPHIA <span>|</span> WASHINGTON, D.C.
                        </p>
                    </div>
                </div>
            </footer>
        <!-- End Footer -->
    </body>
</html>

这是我的functions.js 文件:

(function($)

    /* On Page Ready */

        $(document).ready(function());

    /* On Page Load */

        $(window).load(function()

            // Size differences
                var mainH = $('#main').outerHeight();
                var sheaH = $('#secondary-header').outerHeight();
                $('#secondary').height(mainH + sheaH - 40).hide();

            // Form Validation and Sumbit
                var form   = $('#signup-form');
                form.validate(
                    debug: true,
                    rules: 
                        firstname: 
                             required: true
                        ,
                        lastname: 
                             required: true
                        ,
                        email: 
                             required: true,
                             email: true
                        
                    ,
                    messages: 
                        firstname: 
                            required: "Please enter your first name."
                        ,
                        lastname: 
                            required: "Please enter your last name."
                        ,
                        email: 
                            required: "Please enter your email."
                        
                    ,
                    submitHandler: function(form)
                        form.submit();
                        $('#main, #secondary-header').fadeOut(400);
                        $('#secondary').fadeIn(500);
                        setTimeout(function()
                            window.location.reload(1);
                        , 8000);
                    
                );

        );

    /* On Window Resize */

        $(window).resize(function());

)(window.jQuery);

我正在使用 jQuery 表单验证,验证后它会隐藏表单并显示“谢谢”,然后重新加载页面。现在,如何获取表单数据以保存到 iOS 文件系统?该应用程序需要离线使用并保存信息,这是我需要将信息存储在 iOS 中的原因。

【问题讨论】:

您是否尝试过查看位于docs.phonegap.com/en/edge/cordova_file_file.md.html 的PhoneGap 文档。您需要了解的大部分内容都在此处进行了解释。试试看,如果你卡住了,再来问问。 我有。我在config.xml 中添加了&lt;feature name="File"&gt;&lt;param name="ios-package" value="CDVFile" /&gt;&lt;/feature&gt;&lt;feature name="FileTransfer"&gt;&lt;param name="ios-package" value="CDVFileTransfer" /&gt;&lt;/feature&gt; 以添加FileWriter 支持。猜猜我只是没有绕着它转。比如如何保存字段,从不覆盖现有数据,以及以后如何查看数据。 这是一个在 Cordova/PhoneGap raymondcamden.com/2014/11/05/Cordova-Example-Writing-to-a-file 中文件访问的好例子。至于其余的,你只需要找出一个算法来遵循 1. 读取提交的表单数据,2. 从文件中读取现有存储的数据,3. 将存储的数据与提交的表单数据进行比较,并找出需要更新的数据, 4. 更新它, 5. 将更新后的数据写入文件。 【参考方案1】:

所以我意识到我做这一切都错了。我需要将表单数据发布到数据库。该数据库用于收集所有提交的表单数据。我相信每次提交表单数据时都会覆盖 .txt 文件的想法。所以,我创建了两个页面。填写并提交表格的一页。一页查看所有表单条目以及导出和清除数据库。

index.html

<head>
    <meta charset="utf-8">
    <title>Hall Render - Resources Sign Up</title>
    <!-- Mobile Viewport -->
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <!-- Main Stylesheet -->
        <link href="assets/css/screen.css" media="all" rel="stylesheet" type="text/css">
    <!-- jQuery -->
        <script src="assets/js/jquery-1.11.3-min.js"></script>
        <script src="assets/js/jquery.mobile-1.4.5.min.js"></script>
    <!-- jQuery Plugins -->
        <script src="assets/js/jquery-validation-1.14.0-min.js"></script>
    <!-- Cordova JS -->
        <script src="cordova.js"></script>
    <!-- Functions -->
        <script src="assets/js/functions.js"></script>
        <script type="text/javascript">
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady()
                var db = window.openDatabase("HALLRENDER", 1.0, "App database",200000);
                // Size differences
                    var mainH = $('#main').outerHeight();
                    var sheaH = $('#secondary-header').outerHeight();
                    $('#secondary').height(mainH + sheaH - 40).hide();
                // Form Validation and Sumbit
                    var form   = $('#signup-form');
                    form.validate(
                        debug: true,
                        rules: 
                            firstname: 
                                 required: true
                            ,
                            lastname: 
                                 required: true
                            ,
                            email: 
                                 required: true,
                                 email: true
                            
                        ,
                        messages: 
                            firstname: 
                                required: "Please enter your first name."
                            ,
                            lastname: 
                                required: "Please enter your last name."
                            ,
                            email: 
                                required: "Please enter your email."
                            
                        ,
                        submitHandler: function(form)
                            $('#main, #secondary-header').fadeOut(400);
                            $('#secondary').fadeIn(500);
                            db.transaction(populateDB, errorCB, successCB);
                        
                    );
            
            // Populate the database
                function populateDB(tx) 
                    // Form Variables
                        var firstName    = $('#cfirst-name').val();
                        var lastName     = $('#clast-name').val();
                        var organization = $('#corganization').val();
                        var title        = $('#ctitle').val();
                        var email        = $('#cemail').val();

                    tx.executeSql('CREATE TABLE IF NOT EXISTS PEOPLE (Email, FirstName, LastName, Title, Organization)');
                    tx.executeSql('INSERT INTO PEOPLE (Email, FirstName, LastName, Title, Organization) VALUES ("'+email+'", "'+firstName+'", "'+lastName+'", "'+title+'", "'+organization+'")');

                    setTimeout(function()
                        window.location.reload(1);
                    , 8000);
                
            // Transaction error callback
                function errorCB(tx, err) 
                    alert("Error processing SQL: "+err);
                
            // Transaction success callback
                function successCB() 
                    console.log("Entry saved!");
            
        </script>
</head>
<body onload="onDeviceReady()">
    <!-- Begin Header -->
        <header>
            <div class="wrap">
                <!-- SOMETHING -->
            </div>
        </header>
    <!-- End Header -->
    <!-- Begin Secondary Header -->
        <section id="secondary-header">
            <div class="wrap">
                <div class="inner-wrap">
                    <!-- SOMETHING -->
                </div>
            </div>
        </section>
    <!-- End Secondary Header -->
    <!-- Begin Main -->
        <section id="main">
            <div class="wrap">
                <div class="inner-wrap">
                    <div class="text">
                        <!-- SOMETHING -->
                    </div>
                    <form id="signup-form">
                        <fieldset>
                            <div class="label-input-wrap">
                                <label for="cfirst-name">First Name: (required)</label>
                                <input type="text" id="cfirst-name" name="firstname" tabindex="1">
                            </div>
                            <div class="label-input-wrap">
                                <label for="clast-name">Last Name: (required)</label>
                                <input type="text" id="clast-name" name="lastname" tabindex="2">
                            </div>
                            <div class="label-input-wrap">
                                <label for="corganization">Organization:</label>
                                <input type="text" id="corganization" name="organization" tabindex="3">
                            </div>
                            <div class="label-input-wrap">
                                <label for="ctitle">Title:</label>
                                <input type="text" id="ctitle" name="title" tabindex="4">
                            </div>
                            <div class="label-input-wrap">
                                <label for="cemail">Email: (required)</label>
                                <input type="email" id="cemail" name="email" tabindex="5">
                            </div>
                            <input id="form-submit" type="submit" value="Sign Up" tabindex="6">
                        </fieldset>
                    </form>
                </div>
            </div>
        </section>
    <!-- End Main -->
    <!-- Begin Secondary -->
        <section id="secondary">
            <div class="wrap">
                <div class="inner-wrap">
                    <div class="text">
                        <h3>Thank You</h3>
                    </div>
                </div>
            </div>
        </section>
    <!-- End Secondary -->
</body>

export.html

<head>
    <meta charset="utf-8">
    <title>Hall Render - Export</title>
    <!-- Mobile Viewport -->
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <!-- Main Stylesheet -->
        <link href="assets/css/screen.css" media="all" rel="stylesheet" type="text/css">
    <!-- jQuery -->
        <script src="assets/js/jquery-1.11.3-min.js"></script>
    <!-- jQuery Plugins -->
        <script src="assets/js/jquery-validation-1.14.0-min.js"></script>
    <!-- Cordova JS -->
        <script src="cordova.js"></script>
    <!-- Functions -->
        <script type="text/javascript">
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady()
                var db = window.openDatabase("HALLRENDER", 1.0, "App database",200000);
                db.transaction(queryDB);
                $('#dump').click(function()
                    db.transaction(dropDB);
                    alert('Database Cleared!');
                );
            
            // Query Table Rows
                function queryDB(tx) 
                    tx.executeSql('SELECT * FROM PEOPLE', [], querySuccess);
                
            // Get Table Rows
                function querySuccess(tx,result)
                    var status = document.getElementById("status");
                    var people = "";
                    var len = result.rows.length;
                    for (var i=0; i<len; i++)
                        people = people + '<li>'+result.rows.item(i).Email+','+result.rows.item(i).FirstName+','+result.rows.item(i).LastName+','+result.rows.item(i).Title+','+result.rows.item(i).Organization+'</li>';
                    
                    status.innerHTML = people;
                    $("#status").listview("refresh");
                
            // Delete Database
                function dropDB(tx) 
                    tx.executeSql('DROP TABLE PEOPLE');
                

            // File Writer
                function saveCourseToFile() 
                    console.log("checkpoint 1");
                    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError);
                    alert('CSV File Created!');
                
                function onFSSuccess(fileSystem) 
                    console.log("checkpoint 2");
                    console.log("Opened file system: " + fileSystem.name);
                    fileSystem.root.getFile("export.csv", create:true, exclusive:false, gotFileEntry, onFSError);
                
                function gotFileEntry(fileEntry) 
                    console.log("checkpoint 3");
                    fileEntry.createWriter(gotFileWriter, onFSError);
                
                function gotFileWriter(writer) 
                    var entries =   $('#status').find('li').filter(function() 
                                        return $(this).find('ul').length === 0;
                                    ).map(function(i, e) 
                                        return $(this).text();
                                    ).get().join('\n');
                    var dbEntries = 'Email,First Name,Last Name,Title,Organization\n'+entries;
                    writer.onwrite = function(evt) 
                    console.log("checkpoint 4: write success!");
                    ;
                    writer.write(dbEntries);
                
                function onFSError(err) 
                    console.log(err.code);
                
        </script>
</head>
<body onload="onDeviceReady()">
    <div class="inner-wrap">
        <ol id="status" nam="status"></ol>
        <div class="clear"></div>
        <button id="export" onclick="saveCourseToFile()">Create .csv File Export</button>
        <div class="clear"></div>
        <button id="dump">Clear Database</button>
        <p id="warning"><strong>WARNING: </strong>Export to .csv <em>BEFORE</em> clearing database!!</p>
        <div class="clear"></div>
        <div id="contents"></div>
    </div>
</body>

这可能看起来很疯狂。但是,它适用于我想要完成的工作。获取表单数据,将其保存在本地,然后将信息导出到 .csv 文件中。希望这能让其他人对类似问题有所了解。感谢大家的帮助!!

【讨论】:

【参考方案2】:

首先安装cordova 文件插件。 http://docs.phonegap.com/en/edge/cordova_file_file.md.html

cordova plugin install org.apache.cordova.file

使用 JQuery (#id).val() 或 document.getElementById('id').value 从表单 HTML 中捕获文本。

像这样创建写入文件的函数:

我从表单中获取的数据

var dataForm = $('#someId).val(); // All your text from the form.

需要文件系统和创建文件的功能。

function createTxtFile()
      //  Request File System
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem)
        fileSystem.root.getFile("myTxt.txt", create: true, exclusive: false,
           function(fileEntry)
          // Create File
          fileEntry.createWriter(WriteText, fail);
      , fail);
    ,
    fail
    );
  

写入文本的功能。

  function WriteText(writer) 
      writer.onwriteend = function(evt) // Fired when end write.
        console.log("End write text in file");

    ;
    writer.write(dataForm);

【讨论】:

好的。这有很大帮助。不确定我是否可以正常工作。它在哪里保存或创建文本文件? /Users/YourUser/Library/Application Support/iPhone Simulator/5.0/Applications/CF2A9018-49B9-4DE6-91FC-EA76CB435FC8/Documents/ 但这可能因操作系统版本而异

以上是关于Phonegap保存HTML表单数据的txt文件的主要内容,如果未能解决你的问题,请参考以下文章

使用表单插入 PhoneGap 数据库

使用 phonegap 提交数据和图像的表单

Phonegap混合iOS应用程序中加载的远程网页可以将数据保存到iOS文件系统吗?

如何将表单数据保存到文本文件?

关于怎么将数据保存到txt文件中的问题

在 phonegap 中存储表单详细信息并在在线时发送