如何从localStorage检索信息以传递给数据库

时间:2017-05-28 04:17:54

标签: javascript html5 local-storage

我正在尝试从localStorage获取信息以传递到我的应用程序中的数据库。我在控制台中键入“localStorage”,它显示正确的值,所以我相信它可以用于检索。但是,由于某种原因,我无法获取数据。现在,变量rfidText由键盘输入设置。我想通过抓取localStorage中“userID”中的字符串来设置它。下面我在评论中说我尝试了什么是行不通的。我在file1中调用localStorage.setItem(),在file2中调用localStorage.getItem():任何想法为什么?我的文件1的javascript是:

/*jslint browser: true*/
/*global $, jQuery*/

$(document).ready(function () {

    "use strict";
    var scanned = false,
    scannedInput = [];

    $(window).keypress(function (scanEvent) {

        if (scanEvent.which >= 48 && scanEvent.which <= 57) {
            scannedInput.push(String.fromCharCode(scanEvent.which));
        }

        setTimeout(function () {

            if (scannedInput.length === 10) {

                var userID = scannedInput.join("");
                scanned = true;
                window.localStorage.setItem('userID', userID);
                $("#userId").val(userID);

                if (scanned) {
                    window.location.href = "../html/registration.html";
                }
            }

        scannedInput = [];

        }, 500);
    });
});

文件2 javascript是:

console.log(window.localStorage.getItem('userID')); // this prints
var rfidText = window.localStorage.getItem('userID');
console.log(rfidText);  // this doesn't print

var avatarText = "";

var config = {
    apiKey: xxx  //private info
    authDomain: xxx //private info
    databaseURL: xxx //private info
    storageBucket: xxx //private info
};

firebase.initializeApp(config);

var database = firebase.database();

function setAvatar(avatarName) {
    avatarText = avatarName;
    console.log(avatarText);
}

function writeToFirebase(idInput, languageInput, avatarInput, nameInput, 
ageGroupInput) {

    database.ref("RFID/" + idInput).set({
        id: idInput,
        language: languageInput,
        avatar: avatarInput,
        name: nameInput,
    ageGroup: ageGroupInput,
});
}

function update() {

    var rfidText = document.getElementById("rfidInput").value;

    /* instead of the line above, I want to set rfidText with this line
    var rfidText = localStorage.getItem("userID");  << doesn't work */

    var languageText = document.getElementById("languageInput").value;
    var nameText = document.getElementById("nameInput").value;
    var ageGroupText = document.getElementById("ageGroupInput").value;

    writeToFirebase(rfidText, languageText, avatarText, nameText, 
    ageGroupText);
}

2 个答案:

答案 0 :(得分:0)

这样的事情:

localStorage.getItem("key");

完整示例:

<!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

此示例可在此链接中进行测试:https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webstorage_local

有关本地存储的更多信息,请查看此链接https://www.w3schools.com/html/html5_webstorage.asp

对于本地存储中的多次保存,您可以使用链接中的示例:https://www.w3schools.com/code/tryit.asp?filename=FG2UNYNWBO2D

<!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    localStorage.setItem("firstname", "Luis");
    localStorage.setItem("age", "28 years hold");
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("firstname")+" "+localStorage.getItem("lastname")+" "+localStorage.getItem("age");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

如果您愿意,可以保存json,例如链接https://www.w3schools.com/code/tryit.asp?filename=FG2VMMBWMZW6

<!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
var string = {"firstname":"Luis", "lastname": "Smith", "Age": "28 years old"};
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("data", JSON.stringify(string));
    // Retrieve
    console.debug(localStorage.getItem("data"));
    var objdata = JSON.parse(localStorage.getItem("data"));
    console.debug(objdata);
    document.getElementById("result").innerHTML = objdata.firstname + "  "+ objdata.lastname + " " + objdata.Age;
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

按步骤说明:

1)创建一个json {"firstname":"Luis", "lastname": "Smith", "Age": "28 years old"};

2)将json保存为本地存储localStorage.setItem("data", JSON.stringify(string));

中的字符串

3)从存储中获取数据并使用json解析var objdata = JSON.parse(localStorage.getItem("data"));

4)使用Json objdata.Age

中的数据

对于Json中的多画面数据,例如链接https://www.w3schools.com/code/tryit.asp?filename=FG2VX2M9XKMR

中的示例
<!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
var string = {"firstname":["Luis","Peter"], "lastname": ["Smith","Maerques"], "Age": ["28 years old", "29 years old"]};
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("data", JSON.stringify(string));
    // Retrieve
    console.debug(localStorage.getItem("data"));
    var objdata = JSON.parse(localStorage.getItem("data"));
    console.debug(objdata);
    document.getElementById("result").innerHTML = objdata.firstname[1] + " " + objdata.lastname[0] + " " + objdata.Age[1];
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

与前一个示例的不同之处在于,现在我将数据数组保存在我的Json中。

JSON:

 {"firstname":["Luis","Peter"], "lastname": ["Smith","Maerques"], "Age": ["28 years old", "29 years old"]};

使用Json数据时,必须输入索引数组的编号。

objdata.firstname[1]

如果您想要数组的大小,请使用此代码

objdata.firstname.length

如有任何问题,请问我会尽力回答。

答案 1 :(得分:0)

您可以使用localStorage.setItem("key","value");

进行设置

您可以使用localStorage.getItem("key");

来获取它

您可以使用localStorage.removeItem("key");

将其删除