【问题标题】:Ajax retrieve data from Mysql - Not working properlyAjax 从 Mysql 检索数据 - 无法正常工作
【发布时间】:2011-04-26 14:14:38
【问题描述】:

我正在学习 AJAX,我正在尝试重新创建这个相当简单的示例:

http://www.w3schools.com/php/php_ajax_database.asp

我创建了这个数据库:

所以现在重新创建我刚刚复制并粘贴代码的示例:

index.html

<html>
<head>
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Juan</option>
<option value="2">Manuel</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

和getuser.php

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

现在奇怪的是,当我转到 index.html 时,我可以看到年龄、家乡和工作,但看不到 Firstname 和 Lastname:

我意识到这可能是一个非常基本的错误,但我找不到解决方法。

很抱歉,我不得不粘贴这么多代码,但我没有看到任何其他方式可以解释我的问题,您可以帮助我。

提前非常感谢!

【问题讨论】:

    标签: php mysql database ajax


    【解决方案1】:

    你正在使用

    FirstName  LastName
    

    而不是

    Firstname  Lastname
    

    数组索引区分大小写。

    【讨论】:

    • 天哪,我实际上是在点击我的屏幕,这该死的 php 不区分大小写的狂热。非常感谢!解决了更多问题!
    • 顺便说一句,在我看到那个错误之前,冰盖已经融化了!再次感谢!
    • @Trufa 没关系 - 根据经验,它只会发生一次或两次,然后它会存储在你的直觉记忆中 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多