简体   繁体   中英

Sending message from HTML input box using ajax and showing response

When i load this file on my server and launch the address from my browser the input field is showing and working but when I enter a new string I dont get a response back.

<!DOCTYPE html>
<html>
<body>

<h2>Sending / retrieving a message with AJAX</h2>
<label for="name">Enter message below:</label><BR>
<input type="text" id="msgID" name="name" onchange="loadDoc()" required minlength="1" size="30">

<p id="demo"></p>

<script>
var newmsg = document.getElementById("msgID").value;
var blob = new Blob([newmsg], {type: 'text/plain'});
var url = URL.createObjectURL(blob);
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
</script>

</body>
</html>

Your url is not updated onchange. You should update the url with the value from msgID and send XMLHttpRequest on the new url.

<!DOCTYPE html>
<html>
<body>

<h2>Sending / retrieving a message with AJAX</h2>
<label for="name">Enter message below:</label><BR>
<input type="text" id="msgID" name="name" onchange="loadDoc()" required minlength="1" size="30">

<p id="demo"></p>

<script>
function loadDoc() {
  var newmsg = document.getElementById("msgID").value;
  var blob = new Blob([newmsg], {type: 'text/plain'});
  var url = URL.createObjectURL(blob);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM