当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Unable to save JSON (GeoJSON) data in SQLite in Cordova

问题描述:

I have this code snippet below:

var json_data = document.getElementById("json_data").value;

console.log(json_data);

tx.executeSql('INSERT INTO floodmaps VALUES (?,?,?)', [1, flodMapName, json_data], function(tx, res) {

//console.log(res);

console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");

//console.log(res.rows.item(0).flood_name);

},

function(tx, error) {

console.log('INSERT error: ' + error.message);

});

tx.executeSql('SELECT *FROM floodmaps', [], function(tx, res) {

//console.log(res);

console.log(res.rows.item(0).id);

console.log(res.rows.item(0).flood_name);

console.log(res.rows.item(0).json_data);

},

function(tx, error) {

console.log('error: ' + error.message);

});

What it does is get the value from a input element then save that value into the database. But it does not save, this is the message in the debug console:

rowsAffected: 1 -- should be 1

main.js:208 null

main.js:209 null

main.js:210 null

main.js:241 Transaction Successful

But when I tried using sample data like just a plain text/word, it does save successfully. What could be the problem?

Here's the data.

网友答案:
var json_data = document.getElementById("json_data").value;
console.log(json_data);
var str_json_data=JSON.stringify(json_data);  // my edits
 tx.executeSql('INSERT INTO floodmaps VALUES (?,?,?)', [1, flodMapName, str_json_data], function(tx, res) {
     //console.log(res);
     console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
     //console.log(res.rows.item(0).flood_name);

    if(res.rowsAffected>0){
     tx.executeSql('SELECT * FROM floodmaps', [], function(tx, res) {
     //console.log(res);
       var len = res.rows.length, i;

            for (i = 0; i < len; i++) {
                console.log(res.rows.item(i));
            }
   },
   function(tx, error) {
     console.log('error: ' + error.message);
   });

      }
   },
   function(tx, error) {
     console.log('INSERT error: ' + error.message);
   });

You have to stringify the json object before inserting

分享给朋友:
您可能感兴趣的文章:
随机阅读: