代码之家  ›  专栏  ›  技术社区  ›  Bireon

在JavaScript中将表单值赋给var

  •  -2
  • Bireon  · 技术社区  · 6 年前

    我有一个html表单:

    <label class="sr-only" for="phone">Phone Number </label>
    <input type="text" name="phone" placeholder="eg. 123456XXXXXXXX" class="phone form-control" id="phone">
    </div>
    <div class="f1-buttons">
      <button type="button" class="btn btn-next">Next</button>
    </div>

    <script>var data = "{ \"phone\":\"--this will get value from phone ID field\", \"tenantID\":\"0\" }"; .....</script>
    

    尝试使用 document.getElementById("phone").value; 但它不起作用。有什么建议吗?

    						
                var data = "{ \"MSISDN\":\"document.getElementById("phone").value\", \"tenantID\":\"0\" }";
    								var xhr = new XMLHttpRequest();
    								xhr.withCredentials = true;
    
    								xhr.addEventListener("readystatechange", function () {
    								  if (this.readyState === 4) {
    									console.log(this.responseText);
    								  }
    								});
    
    								xhr.open("POST", "https://api/v1/uat/user");
    								xhr.setRequestHeader("accept", "application/json;charset=UTF8");
    								xhr.setRequestHeader("content-type", "application/json");
    								xhr.setRequestHeader("api-key", "12345565");
    								xhr.setRequestHeader("cache-control", "no-cache");
    								xhr.send(data);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
    <fieldset>
      <h4>Please fill phone Number:</h4>
      <div class="form-group">
        <label class="sr-only" for="phone">Phone Number (123456789xxx) </label>
    <input type="text" name="phone" placeholder="eg. 123456789xxx" class="MSISDN form-control" id="phone">
    </div>
    <div class="f1-buttons">
    <button type="button" class="btn btn-next">Next</button>
    </div>
    </fieldset>

    我编辑了我的问题,电话号码字段是在body请求中使用post方法调用API响应。我想做的是,当用户填写完电话号码后,会将其发送到API的URL中,以获得一个有效的响应,该响应将在下一个表单中打印出来

    2 回复  |  直到 6 年前
        1
  •  1
  •   Quentin    6 年前
    var data = "{ \"MSISDN\":\"document.getElementById("phone").value\", \"tenantID\":\"0\" }";
    

    源代码 而不是执行它的结果。

    创建一个对象。为该对象添加值。然后使用库函数对其进行编码。

    var data = {
        MSISDN: document.getElementById("phone").value,
        tenantID: "0"
    };
    var json = JSON.stringify(data);
    
        2
  •  -1
  •   Ricardo Rocha    6 年前

    您正在将JSON赋给一个变量 var data = "{ \"phone\":\"--this will get value from phone ID field\", \"tenantID\":\"0\" }" . 所以,你可以直接访问 data

    console.log(data)
    <script>var data = "{ \"phone\":\"--this will get value from phone ID field\", \"tenantID\":\"0\" }"</script>