如何使用 javascript 将数据加载到表单中


How can I load data to a form using javascript?

我想将数据从MySql数据库加载到HTTP表单当我在文本中输入时,它应该加载该人的姓名

<html>
<head>
    <script type="text/javascript">
    function FetchUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    var data = JSON.parse(xmlhttp.responseText);
  }
  }
xmlhttp.open("GET","finduser.php?q="+str,true);
xmlhttp.send();
}
this.form.name.value=data.name;
this.form.age.value=data.age;
</script>
</head>
<body>
<form method="post" >
Id<input type="text"  name="id" size="5" />    </br>
Name<input type="text" id="name" name="name"  onclick="Fetchuser(this.form.id.value)" ></br>
Age<input type="text" id="age" name="" size="2" /></br>
</form>
</body>
</html>

PHP代码。

<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '125');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
$sql="SELECT * FROM wow WHERE id = '".$q."'";
$resul = json_encode(mysql_query($sql));
echo $resul;
?> 

我的问题是我怎样才能将姓名和年龄都放在文本框中。我试过这个,但仍然无法加载数据

您可以使用

json_encode返回包含所有相关字段的 json,并在 javascript 中将每个字段放在它所属的位置。

$result = json_encode(mysql_query($sql));
echo $result; // don't forget to push the output or responseText is null.

在javascript中:

var data = JSON.parse(xmlhttp.responseText);

然后,您可以使用data.name_of_the_field访问您的数据

 <?php
 $rs=mysql_fetch_object($result );
 $name=$rs->name;
 $age=$rs->age;
 ?>
  Name<input type="text" name="name"  value="<?php echo $name;?>" />
  Age<input type="text" name="" size="2" value="<?php echo $age;?>"  />

文本框中放置一个id,如<input id="name"<input id="age",以便您可以通过document.getElementById("name")分配它们,document.getElementById("age")