gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:41:16 26 4
gpt4 key购买 nike

我正在尝试从 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);
}

最佳答案

您可以使用 localStorage.setItem("key","value"); 进行设置

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

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

删除它

关于javascript - 如何从 localStorage 中检索信息以传递给数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44223768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com