将变量传递给对象

时间:2020-05-15 13:10:30

标签: javascript firebase object

我正在尝试访问文本字段中的值,并使用其协议将其发送到FIREBASE api。以下是我的HTML页面中的代码(问题代码显示为<----):

Phone number: <input type="text" id="phone"> Message: <input type="text" id="say">
<br><br>
<button onclick="myFunction()">Send</button>
<p id="demo"></p>

<script>
  function myFunction(number) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'key=AAAAuA5S******');

    var body = `{
      "to": "cVv1_TyGS228********89Cog2qG6j8IF",
      "data": {
        "phone": "98668******",
        "say": document.getElementById("say").value //<---- problem here
      }
    }`;

    const init = {
      method: 'POST',
      headers,
      body
    };
    fetch('https://fcm.googleapis.com/fcm/send', init)
      .then((response) => {
        return response.json();
      })
      .then((text) => {
        // text is the response body
        document.getElementById("demo").innerHTML = text;
      })
      .catch((e) => {
        // error in e.message
        document.getElementById("demo").innerHTML = e.message;
      });

  }
</script>

但是,代码在显示的位置中断。如果我对变量进行硬编码(例如“某些值”),则效果很好。如何从“ body”对象内的文本字段访问值。 谢谢..

2 个答案:

答案 0 :(得分:3)

我不太了解,为什么您的对象实际上是字符串。

您可以通过删除字符串文字(反引号)来解决此问题:

const body = {
    say: document.getElementById("say").value
}

或通过使用插值:

const body = `{
    say: ${document.getElementById("say").value}
}`

但是,如果您真的希望对象成为字符串,可以使用JSON.stringify()

答案 1 :(得分:-2)

弄乱了四个小时,意识到我犯了一个愚蠢的错误。 (玛丽亚的第二个解决方案派上了用场)。我只是显示更正的部分:

const body = `{
    "to": "cVv1_**********fXT89Cog2qG6j8IF",
    "data": {
    "phone": $"{document.getElementById("phone").value}",
    "say": $"{document.getElementById("say").value}"  //<--- added the quotations
      }
}`;

就是这样。我忘记了简单的引号。添加此答案,以使像我这样的菜鸟将来不会再为这样简单的事情浪费时间