AJAX, refresh INPUT field

2019-08-05 06:37发布

问题:

I am using AJAX for the first time with PHP and mySQL. I have been following some examples and tutorials on how to use AJAX with INPUT fields.

I have a form with 2 input fields.

  • 1st input field: User type in 4 digits
  • 2nd input field: The 4 digits are looked up in the mySQL db and outputted on this field.

Most examples are based on output in div's and span's while i am interested in output on my 2nd INPUT field.

How is this possible?

My js-file:

function showUser(str)
{
  if (str=="")
  {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest)
  {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","include/postalcode.php?q="+str,true);
  xmlhttp.send();
}

回答1:

Most examples are based on output in div's and span's while i am interested in output on my 2nd INPUT field.

You should be able to follow the examples with two changes:

  • use .value instead of .innerHTML for input fields
  • look up your second input field by its ID

document.getElementById("secondFieldId").value=xmlhttp.responseText;



回答2:

You have written :

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

Instead of innetHTML use value:

document.getElementById("txtHint").value=xmlhttp.responseText;


标签: php ajax input