javascript - 我无法在 javascript 中从 firebase 中获取数据

标签 javascript json firebase

我正在尝试从 firebase 中获取数据以用于用 JS 编写的游戏。问题是我永远无法获取数据。这是我在编辑器中添加的 JSON:

{xcord: 23, ycord: 3543}

这是我用来尝试获取数据的 JS 代码:

fb.on('child_added', function(snapshot) {
    obj = snapshot.val();
    alert(obj.xcord);
        c1.x = obj.xcord;
        c1.y = obj.ycord;
        stage.update();
});

当警报弹出时,我得到的只是“undefind”。谁知道怎么了?

最佳答案

当我console.log jsbin 中的数据时,它显示为:

{sfws: "{xcord: 23, ycord: 3543}", update: "{xcord:'3435'}", update2: "{xcord: 23, ycord: 3543}"}

注意到坐标周围的那些双引号了吗?这意味着它们是字符串,而不是 JSON 对象。

我猜你用这样的东西存储它们:

var coords = document.getElementById('editor').value; // read the text from the input
ref.set(coords);

您从输入中读取的任何值都将是一个字符串,即使在人眼看来它非常接近 JavaScript 对象。

您需要将值从字符串转换为 JavaScript 对象,这可以使用 JSON.parse 轻松完成。这要求您将对象作为正确的 JSON 输入,这意味着您需要将属性名称用双引号引起来:

'{"xcord": 23, "ycord": 3543}'

然后,您可以在将值发送到 Firebase 之前将此 JSON 解析回对象:

var text = document.getElementById('editor').value; // read the text from the input
var coords = JSON.parse(text);
ref.set(coords);

或者当您从 Firebase 检索字符串时:

fb.on('child_added', function(snapshot) {
    var text = snapshot.val();
    var obj = JSON.parse(text);
    alert(obj.xcord);
    c1.x = obj.xcord;
    c1.y = obj.ycord;
    stage.update();
})

快速修复(不推荐)

如果您不愿意将数据转换为正确的 JSON,您也可以使用 eval 将其恢复原状。我强烈建议不要这样做,因为 eval 不仅对引号不那么挑剔;它还将允许将代码片段注入(inject)您的页面。但如果您想忽略该建议,这是快速解决方法:

fb.on('child_added', function(snapshot) {
    var text = snapshot.val();
    eval("obj = "+text);
    alert(obj.xcord);
    c1.x = obj.xcord;
    c1.y = obj.ycord;
    stage.update();
})

关于javascript - 我无法在 javascript 中从 firebase 中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220495/

相关文章:

node.js - 使用 Cloud Functions 的下载网址从 Firebase 存储中删除文件

javascript - 用于压缩 javascript 和缩小图像的 Windows 程序

javascript - jQuery 与 Joomla YooTheme WidgetKit 冲突

json - 将未知的 Encodable 枚举值解码为默认值

json - 如何在 vscode 中获取 Protractor 或 json 智能感知

java - 当 Firebase 中的值发生更改时,Sharedpreferences 值会更新

Javascript Promise 链问题 (Ember)

Javascript setInterval 随机停止

java - ObjectMapper-无法反序列化实例 java.lang.Double

firebase - PluginRegistry 中的注册器已被弃用