簡體   English   中英

在phonegap中使用sqlite插件時出現Ajax錯誤

[英]Ajax error when using sqlite plugin in phonegap

我正在制作一個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>

Index.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>

我可以在不使用插件的情況下使用sqlite進行幫助,但您的問題尚不清楚,無法知道該解決方案是否可以提供。請解釋一下您要使用不使用插件的sqlite進行哪些操作

我將幫助您創建一個示例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,因為bcos我創建了兩個單獨的文件)

 <!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>

這將解決您的問題; 只需進行一些編輯即可使其適用於您的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM