Javascript-从输入中动态添加一个值到GET网址

时间:2019-06-27 06:44:38

标签: javascript xmlhttprequest

我有3个简单的输入字段

我需要输入动态添加到 GET 请求,我需要使用只能使用香草js

我的HTML

<div class="action-container">
    <div class="action">
        <input class="input" id="player1" type="text">
        <div class="button" onclick="submit()">Submit</div>        
    </div>
    <div class="action">
        <input class="input" id="player2" type="text">
        <div class="button" onclick="submit()">Submit</div>
    </div>
    <div class="action">
        <input class="input" id="player3" type="text">
        <div class="button" onclick="submit()">Submit</div>
    </div>
</div>

我的JS

function submit(){
    var http = new XMLHttpRequest();

    var guessPlayer1 = document.getElementById('player1').value
    var guessPlayer2 = document.getElementById('player2').value
    var guessPlayer3 = document.getElementById('player3').value

    http.onreadystatechange = function(){
        if(http.readyState == 4 && http.status == 200){
            console.log(http.response)
        }
    }

    http.open("GET", "https://Dummy-End-Point.com/" + guessPlayer1, true);
    http.send();

}

2 个答案:

答案 0 :(得分:1)

更改submit(),使其将ID作为参数。

function submit(id) {
  var http = new XMLHttpRequest();

  var guess = document.getElementById(id).value

  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      console.log(http.response)
    }
  }

  http.open("GET", "https://Dummy-End-Point.com/" + guess, true);
  http.send();

}
<div class="action-container">
  <div class="action">
    <input class="input" id="player1" type="text">
    <div class="button" onclick="submit('player1')">Submit</div>
  </div>
  <div class="action">
    <input class="input" id="player2" type="text">
    <div class="button" onclick="submit('player2')">Submit</div>
  </div>
  <div class="action">
    <input class="input" id="player3" type="text">
    <div class="button" onclick="submit('player3')">Submit</div>
  </div>
</div>

答案 1 :(得分:1)

<div class="action-container">
    <div class="action">
        <input class="input" id="player1" type="text">
        <div class="button" onclick="submit(this)">Submit</div>        
    </div>
    <div class="action">
        <input class="input" id="player2" type="text">
        <div class="button" onclick="submit(this)">Submit</div>
    </div>
    <div class="action">
        <input class="input" id="player3" type="text">
        <div class="button" onclick="submit(this)">Submit</div>
    </div>
</div>

function submit(elem) {
  var http = new XMLHttpRequest();

  var guess = elem.parentElement.getElementsByTagName("input")[0].id; 

  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      console.log(http.response)
    }
  }

  http.open("GET", "https://Dummy-End-Point.com/" + guess, true);
  http.send();

}