我正在学习W3学校的本教程。虽然大多数情况下一切都很好,但它似乎没有从我创建的MySQL数据库中返回任何实际信息,在exercisedb
数据库中称为exercises
。
以下是index.php
的代码
<head>
<title>
Database Fetch Demo
</title>
<script>
function showExercise(str) {
if (str == "") {
document.getElementById("txtPlaceholder").innerHTML = "";
return;
} else {
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("txtPlaceholder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getexercise.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="exercises" onchange="showExercise(this.value)">
<option value="">Choose an Exercise</option>
<option value="1">Bench Press</option>
<option value="2">Deadlift</option>
<option value="3">Barbell Squat</option>
</select>
</form>
<br>
<div id="txtPlaceholder">
<b>No exercise selected.</b>
</div>
<body>
</html>
下面是getexercise.php
的代码
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table td, td{
border: 1px solid black;
padding: 5px;
}
th {text-align: left};
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$connect = mysqli_connect('localhost','root','root','exercisedb');
if(!$connect){
die('Could not connect ' . mysqli_error($connect));
}
mysqli_select_db($connect, "exercisedb");
$sql = "SELECT * FROM exercises WHERE id = '".q."'";
$result = mysqli_query($connect, $sql);
echo "<table>
<tr>
<th>Exercise Name</th>
<th>Difficulty</th>
<th>Target Areas</th>
<th>Description</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['difficulty'] . "</td>";
echo "<td>" . $row['targetareas'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
?>
</body>
</html>
您不应该发送
<!DOCTYPE html>
<head>
<body>
在ajax中,只回答您期望的div的内容。