使用JQuery读取文本文件并存储在DataBase

时间:2015-12-24 00:19:34

标签: javascript jquery opendatabase

我有一个包含

的文件
1 : "Benz"
2 : "Bmw"
3 : "Porche"
4 : "Ferrari"

我想用Jquery读取它并将它们存储在OpenDataBase的本地数据库中,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将它们放入数据库中。

感谢。

2 个答案:

答案 0 :(得分:1)

如果可以,请删除文本文件中的数字和引号,不应该使用它们(您的计数器将为您执行此操作)。

将阅读文本文件的代码更改为:

    var file = "file/words.txt";
    function getFile(){
       $.get(file, function(txt){
           var lines = txt.responseText.split("\n");
           for (var i = 0, len = lines.length; i < len; i++) {
               save(lines[i]);
           }
       }); 
    }

现在你的文件的每一行都有一个数组;如果你删除了数字和引号,它应该只是汽车名称。

for (var i = 0; i < lines.length; i++) {
   tx.executeSql('INSERT INTO Car (id, name) VALUES (i, lines[i]);
}

如果您想保持文件不变,请更改以下行,如下所示:

 var lines = txt.responseText.split(":");

现在数组包含数字和车名(奇数是数字,甚至是车名)。 我们可能想要删除双引号(SQL可能会抛出错误):

lines.replace(/"/g, '').trim();

 for (var i = 0; i < lines.length; i++) {
       tx.executeSql('INSERT INTO Car (id, name) VALUES (i, lines[i+1])');
       i++; // we iterate again because we want an odd number 
            // (we skip over one iteration as that'd be the car, and we want the next # instead). 
    }

答案 1 :(得分:1)

这里的代码是你想要的:

$airline_name = "United";
$flight_number = 262;
$departure_airport = "";

function airport($one, $two, $three) {

if ($one =="" && $two =="" && $three =="") {
} else {
    switch(true) {
        case !empty($one):
        $one = "Airline Name: $one<br>";
        case empty($one):
        $one = "Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
        case !empty($two):
        $two = "Flight Number: $two<br>";
        case empty($two):
        $two = "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
        case !empty($three):
        $three = "Departure Airport: $three<br>";
        case empty($three):
        $three = "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
    }

    }
echo $one, $two, $three;
}

airport($airline_name,$flight_number,$departure_airport);

?>

输出:

enter image description here