AJAX从数据库中检索数据

时间:2016-08-16 11:20:51

标签: javascript php ajax

我尝试使用AJAX从数据库bu中检索数据,但是我收到了错误。因为我是新来的,所以不知道我的问题在哪里 HTML&& JS代码在这里



<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <script>
    function user(str){
      if(str.length==0)
      {
        document.getElementById("userhint").innerHTML = "";
        return;
      }	
      else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                  document.getElementById("userhint").innerHTML = xmlhttp.responseText;
              }
          }
          xmlhttp.open("GET", "ajaxdb.php?q=" + str, true);
          xmlhttp.send();
        }
      }
    </script>
  </head>
  <body>
    <p><b>Select any name from below list</b></p>
    <form>
      <select name="users" onChange="user(this.value)">
        <option value="">Select Person</option>
        <option value="1">Mujtaba</option>
        <option value="2">Masroor</option>
        <option value="3">Mustafa</option>
      </select>
    </form>
    <br />
    <div id="userhint"><b>User info will be listed here...</b></div>
  </body>
</html>
&#13;
&#13;
&#13;

和PHP代码在这里

&#13;
&#13;
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style>
    table {
        width: 100%;
        border-collapse: collapse;
    }

    table, td, th {
        border: 1px solid black;
        padding: 5px;
    }

    th {text-align: left;}
    </style>
  </head>
  <body>
  <?php
  $q = intval($_GET['q']);
  $servername = "localhost";
  $username = "root";
  $password = "";
  $conn = mysql_connect($servername, $username, $password);
  if (!$conn) {
    die('Could not connect: ' . mysqli_error($conn));
  }
  mysqli_select_db($conn, "firstdb");
  $sql = "SELECT * FROM name WHERE id = '" . $q . "'";
  $result = mysqli_query($conn, $sql);
  echo "<table>
    <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Gender</th>
    </tr>";
    while ($row = mysqli_fetch_array($result)) {
      echo "<tr>";
      echo "<td>" . $row['name'] . "</td>";
      echo "<td>" . $row['age'] . "</td>";
      echo "<td>" . $row['sex'] . "</td>";
      echo "</tr>";
    }
  echo "</table>";
  mysqli_close($conn);
  ?>
  </body>
</html>
&#13;
&#13;
&#13;

错误

enter image description here

数据库列

enter image description here

0 个答案:

没有答案