Firebase保存多个数据

时间:2018-03-03 14:01:08

标签: javascript firebase firebase-realtime-database

我是使用Google Firebase的新手。我已经设法添加实时保存数据功能,但我想保存我拥有的数据。请有人指导我走正确的道路吗?

以下是.JS文件中的代码:

var btn = document.getElementById(btn);

var weight, height, measure, bmi, error ;

function calculate() {

    var firebaseRef = firebase.database().ref();

    firebaseRef.child("BMI").set("BMI Values");

    weight = document.getElementById("weight").value;
    height = document.getElementById("height").value;
    error = "Please enter some values";
    height /= 100;
    height *= height;
    bmi = weight/height;
    bmi = bmi.toFixed(1);

    if (bmi <= 18.4) {
        measure = "Your BMI is " + bmi + " which means " + "you are Underweight";
    } else if (bmi >= 18.5 && bmi <= 24.9) {
        measure = "Your BMI is " + bmi + " which means " + "You are Normal";
    } else if (bmi >= 25 && bmi <= 29.9) {
        measure = "Your BMI is " + bmi + " which means " + "You are Overweight";
    } else if (bmi >= 30) {
        measure = "Your BMI is " + bmi + " which means " + "You are Obese";
    }

    if (weight === 0 ) {
        document.getElementById("results").innerHTML = error;
    } else if (height === 0){
        document.getElementById("results").innerHTML = error;
    }
     else {

        document.getElementById("results").innerHTML = measure;
    }
    if (weight < 0) {
        document.getElementById("results").innerHTML = "Negative Values not Allowed";
    }
}

1 个答案:

答案 0 :(得分:1)

要将BMI数据添加到数据库,请执行以下操作:

weight = document.getElementById("weight").value;
height = document.getElementById("height").value;
error = "Please enter some values";
height /= 100;
height *= height;
bmi = weight/height;
bmi = bmi.toFixed(1);

firebaseRef.child("BMI").push({
  weight: weight,
  height: height,
  bmi: bmi
});

除了(显然)传入从HTML获得的值之外,此代码调用push(),每次调用时都会在JSON中生成一个新的唯一位置。这样,您输入的值就不会覆盖已存在的值。

请注意,HTML元素通常会将value作为字符串返回。因此,您可能仍需要在从HTML元素获取后将权重和高度转换为数字:

weight = parseFloat(document.getElementById("weight").value);
height = parseFloat(document.getElementById("height").value);

最后:在Firebase documentationFirebase codelab for web developers中详细介绍了将数据保存到Firebase。我强烈建议你检查一下。花了几个小时在那里,节省了许多问题。