我有一个文件包含
1 : "Benz"
2 : "Bmw"
3 : "Porche"
4 : "Ferrari"
我想用Jquery读取它并将它们存储在OpenDataBase的Local Database中,其中1表示步数,Benz表示数据库中的另一个字段。
我读取文件的代码
jQuery.get('file/words.txt', function(data) {
alert(data)
});
和我创建数据库的代码
var db = openDatabase( ’mydb’, ’1.0’,
’database for test’,
2 * 1024 * 1024
);
db.transaction(function (tx) {
tx.executeSql(’CREATE TABLE IF NOT EXISTS Car
(number INT, name VARCHAR(100))’);
});
我不知道如何分隔数据并将它们放入JavaScript中。
谢谢。
这是您想要的代码:
// assume this is your data (I've added the newline as well)
var textData = '1 : "Benz" \n2 : "Bmw" \n3 : "Porche"\n4 : "Ferrari" ';
// turn data into array
var ary = textData.split('\n').map(function(v) {
return v.split(':').map(function(v2) {
// make sure we remove the quotes and spaces
return v2.replace(/"/g, '').trim();
});
})
// function to escape double quotes to prevent sql injection
function escapeSql(str) {
return (typeof str === 'number' ? str : str.replace(/"/g, '"'));
}
// open database
var db = openDatabase('mydb', '1.0', 'database for test', 2 * 1024 * 1024);
// create table
db.transaction(function(tx) {
tx.executeSql('create table if not exists Car(step, make)');
});
// insert data
db.transaction(function(tx) {
// loop through each item and insert the data, notice how we call escapeSql to prevent sql injection
ary.forEach(function(item) {
var sql = 'insert into Car(step, make) values(' + escapeSql(item[0]) + ', "' + escapeSql(item[1]) + '")';
tx.executeSql(sql);
});
});
var sql,
cars = [];
// read data from table
db.transaction(function(tx) {
tx.executeSql('select * from Car', [], function(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
cars.push({
step: results.rows.item(i).step,
make: results.rows.item(i).make
});
}
console.log(cars);
}, null);
});
输出:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句