【问题标题】:Ajax error when using sqlite plugin in phonegap在 phonegap 中使用 sqlite 插件时出现 Ajax 错误
【发布时间】:2016-02-28 18:42:02
【问题描述】:

我正在制作一个 phonegap 应用程序,它通过 ajax 从外部服务器读取 json 数据。我需要在 sqlite 数据库中加载和保存数据。本机 sqlite 生成一个回调函数错误,我在 stackoverflow 上询问过该错误,但没有得到任何答案。然后我决定使用 sqlite 插件,但是当我在我的应用程序中使用它时,ajax 中定义的错误函数会执行。没有插件,它工作得很好。请告诉我如何在没有任何错误的情况下使用带有或不带有插件的 sqlite。这是我正在使用的代码:

              var DB = window.sqlitePlugin.openDatabase({name: "Posts_DB.db"});
              var BASE_URI = "https://public-api.wordpress.com/rest/v1.1/sites/smushbits.com/";
         var POST_OFFSET = 0;


             function getPosts() {
          $.mobile.loading('show');

            $.ajax({
                    url: BASE_URI + "posts",
                     type: "GET",
                       dataType: "json",
                    data: {
                     "number": 10,
                      "offset": POST_OFFSET,
                       "order": "DESC"
                      },
                  error: function() {
                   alert("An error occured.");
                    },
                   success: function(response) {
                   $.each(response.posts, function(index, data) {
                   $('<li><a href="#single" data-transition="slide" id="'+data.ID+'"><h1>'+data.title+'</h1><p>'+getDays(data.date)+'</p></a></li>').appendTo('#latest-list');
                   $(document).on("click", "#"+data.ID, function() {
                showPost(data.title, data.date, data.content, data.URL);
                   });
              });
                $('#latest-list').listview('refresh');
             $.mobile.loading("hide");
                }
              });
         POST_OFFSET+=10;
        }
          document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
        $(document).ready( function() {
        DB.transaction(createTableDB, errorCB, successCB);
         getPosts();
        });
        }

           function createTableDB(tx) {
             tx.executeSql('CREATE TABLE IF NOT EXISTS Posts(id INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT NOT NULL, Date TEXT NOT NULL, Content TEXT NOT NULL, Link TEXT NOT NULL)');
              }

           function populateDB(tx) {
               var title = document.getElementById('entry-title').innerHTML;
              var date = document.getElementById('entry-date').innerHTML;
              var content = document.getElementById('entry').innerHTML;
               var url = document.getElementById('browser').getAttribute('href');
               tx.executeSql('INSERT INTO Posts(Title,Date,Content,Link) VALUES(?,?,?,?)', [title, date, content, url] );
               }


              function errorCB(err) {
                alert("Error processing SQL: "+err.message);
               }


                function successCB() {
                   DB.transaction(queryDB, errorCB);
                }


                 function queryDB(tx){
                   tx.executeSql('SELECT * FROM Posts', [], querySuccess, errorCB);
                  }

             function querySuccess(tx,result){
               $('#saved-articles-list').empty();
              for( var index = 0; index < result.rows.length; index++) {
                     var row = result.rows.item(index);
                    $('#saved-articles-list').append('<li><a id="'+row['id']+'" data-transition="slide" href="#single"><h1 class="ui-li-heading">'+row['Title']+'</h1><p class="ui-li-desc">'+getDays(row['Date'])+'</p></a></li>');
                   $(document).on("click", row['id'], function() {
                    showPost(row['Title'], row['Date'], row['Content'], row['Link']);
             });
           }

           $('#saved-articles-list').listview("refresh");
       }

Config.xml:

           <?xml version="1.0" encoding="UTF-8" ?>
           <widget xmlns   = "http://www.w3.org/ns/widgets"
              xmlns:gap   = "http://phonegap.com/ns/1.0"
             xmlns:android   = "http://schemas.android.com/apk/res/android"
             id          = "com.smushbits.app"
             versionCode = "10" 
             version     = "1.0.0" >

             <!-- versionCode is optional and Android only -->

            <name>TestApp</name>

             <description>
              Test app
            </description>

              <author href="https://smushbits.com/about" email="xyz@gmail.com">
               Vishal Singh 
                </author>
                 <access origin="*" />
               <platform name="android" >
             <preference name="orientation" value="portrait" />
             <preference name="fullscreen" value="true" />
            </platform>
           <feature name="http://api.phonegap.com/1.0/network" />
            <plugin name="com.indigoway.cordova.whitelist.whitelistplugin" source="pgb" />
         <plugin name="cordova-plugin-inappbrowser" spec="1.1.0" />
        <plugin name="io.litehelpers.cordova.sqlite" spec="0.7.10" source="pgb" />
        <plugin name="cordova-plugin-x-socialsharing" spec="5.0.7" />
         <allow-navigation href="http://*/*" />
         <allow-navigation href="https://*/*" />
          <allow-navigation href="data:*" />
          <allow-intent href="*" />
           <icon src="icon.png" />
            <splash src="splash.png" />
            </widget>

索引.html:

      <!DOCTYPE html>
    <html>
    <head>
    <title>SmushBits</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" type="text/css" href="css/jquery.mobile.min.css" >
    <link rel="stylesheet" type="text/css" href="css/app.css" >
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery.mobile.min.js"></script>
    <script src="js/app.js"></script>
    <script src="phonegap.js"></script>
    </head>
    <body onload="init()">
<div id="home" data-role="page" data-theme="a">
<div data-role="header" data-position="fixed" data-theme="b">
<a href="#navpanel1" class="ui-btn ui-btn-left ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-bars"></a>
<h1>SmushBits</h1>
<a href="#search" data-transition="slidedown" class="ui-btn ui-btn-right ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-search"></a>
</div> 
<div data-role="content">
<ul data-role="listview" id="latest-list">
</ul>
</div>
</div>


<div id="single" data-role="page" data-theme="a">
<div data-role="header" data-position="fixed" data-theme="b">
<a href="#navpanel5" class="ui-btn ui-btn-left ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-bars"></a>
<h1>SmushBits</h1>
<a href="#search" data-transition="slidedown" class="ui-btn ui-btn-right ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-search"></a>
</div>
<div data-role="content">
<h1 id="entry-title"></h1>
<div id="save-complete"></div>
<h4 id="entry-date"></h4>
<div data-role="controlgroup" data-type="horizontal">
<a id="save-post" class="ui-btn ui-icon-heart">Save</a><a id="share" class="ui-btn ui-icon-star">Share</a><a href="" id="browser" class="ui-btn ui-icon-navigation">Browse</a></div>
<div id="entry"></div>
</div>
</div>


<div id="saved-articles" data-role="page" data-theme="a">
<div data-role="header" data-position="fixed" data-theme="b">
<a href="#navpanel4" class="ui-btn ui-btn-left ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-bars"></a>
<h1>SmushBits</h1>
<a href="#search" data-transition="slidedown" class="ui-btn ui-btn-right ui-corner-all ui-shadow ui-btn-icon-notext ui-icon-search"></a>
</div>
<div data-role="content">
<ul data-role="listview" id="saved-articles-list" data-split-icon="delete">
</ul>
</div>
</div>

</body>
</html>

【问题讨论】:

    标签: javascript jquery sqlite cordova


    【解决方案1】:

    我将帮助您创建一个示例 sqlite 数据库,您可以使用它来创建、编辑、删除和更新您的数据库,而无需使用 sqlite 插件。

    table.js(你的 javascript 文件)

    var scroll = new iScroll('wrapper', {
     vScrollbar : false,
     hScrollbar : false,
     hScroll : false
    });
    
    
    
            document.addEventListener("deviceready", onDeviceReady, false);
    
            var currentRow;
            // Populate the database
            //
            function populateDB(tx) {
    
    
    
                }
    
            // Query the database
            //
            function queryDB(tx) {
                tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
            }
    
            function searchQueryDB(tx) {
                tx.executeSql("SELECT * FROM DEMO where name like ('%"+ document.getElementById("txtName").value + "%')",
                        [], querySuccess, errorCB);
            }
            // Query the success callback
            //
            function querySuccess(tx, results) {
                var tblText='<table id="t01"><tr><th>ID</th> <th>Name</th> <th>Number</th></tr>';
                var len = results.rows.length;
                for (var i = 0; i < len; i++) {
                    var tmpArgs=results.rows.item(i).id + ",'" + results.rows.item(i).name
                            + "','" + results.rows.item(i).number+"'";
                    tblText +='<tr onclick="goPopup('+ tmpArgs + ');"><td>' + results.rows.item(i).id +'</td><td>'
                            + results.rows.item(i).name +'</td><td>' + results.rows.item(i).number +'</td></tr>';
                }
                tblText +="</table>";
                document.getElementById("tblDiv").innerHTML =tblText;
            }
    
            //Delete query
            function deleteRow(tx) {
              tx.executeSql('DELETE FROM DEMO WHERE id = ' + currentRow, [], queryDB, errorCB);
            }
    
            // Transaction error callback
            //
            function errorCB(err) {
                alert("Error processing SQL: "+err.code);
            }
    
            // Transaction success callback
            //
            function successCB() {
                var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                db.transaction(queryDB, errorCB);
            }
    
             // Cordova is ready
            //
            function onDeviceReady() {
                var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                db.transaction(populateDB, errorCB, successCB);
            }
    
            //Insert query
            //
            function insertDB(tx) {
    
    
     var sql = "CREATE TABLE IF NOT EXISTS DEMO( "+ " id INTEGER PRIMARY KEY AUTOINCREMENT ,"  + "name VARCHAR(50), "
       + "number INT)";
     tx.executeSql(sql);
    
     var Name =document.getElementById("txtName").value;
     var Number = document.getElementById("txtNumber").value;
     tx.executeSql("INSERT INTO DEMO (name,number) VALUES ('"+ Name +"','"+ Number +"' )");
    
    
            }
    
            function goInsert() {
    
    
                 var Name = document.getElementById("txtName").value;
                 var Number = document.getElementById("txtNumber").value;
    
    
                var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                db.transaction(insertDB, errorCB, successCB);
    
    
            }
    
            function goSearch() {
                var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                db.transaction(searchQueryDB, errorCB);
            }
    
            function goDelete() {
                 var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                 db.transaction(deleteRow, errorCB);
                 document.getElementById('qrpopup').style.display='none';
            }
    
            //Show the popup after tapping a row in table
            //
            function goPopup(row,rowname,rownum) {
                currentRow=row;
                document.getElementById("qrpopup").style.display="block";
                document.getElementById("editNameBox").value = rowname;
                document.getElementById("editNumberBox").value = rownum;
            }
    
            function editRow(tx) {
                tx.executeSql('UPDATE DEMO SET name ="'+document.getElementById("editNameBox").value+
                        '", number= "'+document.getElementById("editNumberBox").value+ '" WHERE id = '
                        + currentRow, [], queryDB, errorCB);
            }
            function goEdit() {
                var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
                 db.transaction(editRow, errorCB);
                  document.getElementById('qrpopup').style.display='none';
             }
    

    index.html(请注意,我在这里引用了 table.js,因为我创建了单独的文件)

     <!DOCTYPE html>
    <html> 
    
        <head>
            <title></title>
    
            <style type="text/css">
    
    input[type='text'] {
           border: 1px solid black;
           width: 200px;
           margin-left: 10px;
    }
    table {
        width:100%;
    }
    table, th, td {
                  border: 1px solid black;
                  border-collapse: collapse;
    }
    th, td {
        padding: 5px;
        text-align: left;
    }
    table#t01 tr:nth-child(even) {
        background-color: #eee;
    }
    table#t01 tr:nth-child(odd) {
        background-color:#fff;
    }
    table#t01 th    {
        background-color: black;
        color: white;
    }
    button {
        margin: 10px;
        font: bold 13px "Helvetica Neue", Helvetica, Arial, clean, sans-serif !important;
        text-shadow: 0 -1px 1px rgba(0,0,0,0.25), -2px 0 1px rgba(0,0,0,0.25);
        border-radius: 5px;
        -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
        -moz-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
        -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
        display: inline-block;
        color: white;
        padding: 5px 10px 5px;
        white-space: nowrap;
        text-decoration: none;
        cursor: pointer;
        background-color: #BE3E76;
        border-style: none;
        text-align: center;
        overflow: visible;
    }
    
    button:active {
        background-position: 0 -100px;
        -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.7);
        -webkit-box-shadow: none;
    }
    
    #qrpopup {
        position:fixed;z-index:9999;background-color:rgba(0, 0, 0,0.9);width:100%; height:100%;display:none;
    }
    
    
    </style>
    
      <script type="text/javascript" src="js/libs/tables.js"></script>    
        </head>
    
    <body>
        <h1>TABLES </h1>
        <p>Open Database</p>
        <div id="qrpopup" > //The hidden div tag for implementing the popup
                <hr/>
                <input type="text" id="editNameBox"><br>
                <input type="text" id="editNumberBox"><br>
                <button onclick="goDelete()">Delete</button>
                <button onclick="goEdit()">Edit</button>
                <button onclick="document.getElementById('qrpopup').style.display='none';">Discard</button>
        </div>
    
        <div>
            Name<input type="text" value="Name" id="txtName">
            Number<input type="text" value="123" id="txtNumber"><hr/>
        </div>
    
        <div style="text-align: center">
            <button onclick="goInsert()">Insert</button>
            <button onclick="goSearch()">Search</button>
            <button onclick="successCB()">Show All</button>
            <a href="#" onclick="window.open('http://www.wikipedia.org','_self','location=yes')">Wikipedia (webview)</a>
    
        </div>
    
    
          <div id="tblDiv"></div>
    
      </body>
      </html>
    

    这将解决您的问题;只需进行一些编辑,使其适用于您的项目。

    【讨论】:

      【解决方案2】:

      我可以帮助在没有插件的情况下使用 sqlite,但是您的问题不够清楚,无法知道我要提供的解决方案。请解释一下您想要使用不使用插件的 sqlite 进行哪些操作

      【讨论】:

      • 我想存储我通过 ajax 从服务器加载的文章。我该怎么做?
      • 好的@vishal,我会给你一个例子,当我在电脑上时可以使用它。也向我提供你的 index.html 详细信息
      • 我在上面添加了我的index.html的源代码。
      • 它正常工作。谢谢! :) 我想再问一个问题,是否需要在 deviceready 回调函数中设置数据库事务?
      • 是的!它正在工作。我使用以下内容:window.open(encodeURI(url), "_system", "location=no")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多