【发布时间】:2016-12-30 19:13:44
【问题描述】:
我正在尝试将 AJAX 与 php 和 MySqli 一起使用以从数据库中获取结果。我对 ajax 和 javascript 很陌生,所以任何帮助都会得到帮助
这是我的表格:
<form method="get">
<input type="number" min=0 name="gameId" id="gameId" placeholder="Game Id" required><br>
<input type="number" min=0 step=0.01 name="price" id="price" placeholder="Price" required><br>
<button type="submit" onClick="getGames()">Submit</button>
</form>
这是我在 JS 中的 AJAX:
function getGames() {
var gameId = document.getElementById("gameId").value;
var price = document.getElementById("price").value;
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("jumbotron").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getGames.php?gameId="+gameId+"&price="+price, true);
xmlhttp.send();
}
这是我的 php
<?php
$servername = "localhost";
$serverusername = "root";
$dbname = "ryangames";
$gameId = intval($_GET["gameId"]);
$price = intval($_GET["price"]);
$conn = mysqli_connect($servername, $serverusername, "", $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM GAMES WHERE GameId = ".$gameId." AND Price = ".$price;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class=\"gameHolder\">
<img class=\"gameImg\" src=\"images/".$row["Code"].".png\" alt=\"".$row["Name"]."\">
<div class=\"gameText\">
<h3 class=\"gameName\">".$row["Name"]."</h3>
<p class=\"gameDesc\">".$row["Description"]."</p>";
if ($row["Price"] == 0) {
echo "<p class=\"gamePrice\">FREE</p>";
} else {
echo "<p class=\"gamePrice\">£".$row["Price"]."</p>";
}
echo" </div>
</div>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
我可以看到地址中的值,但没有任何反应。如果我只包含在 php 中并让用户每次都刷新,则该查询有效。
更新:将两个 getElementByIds 都更改为末尾有 .value
【问题讨论】:
-
您在浏览器中看到的内容 inspect element network 选项卡的 getGames.php。点击它并查看 response 选项卡
-
当我转到 getGames.php 时,我得到 GameId 和 Price 的未定义索引。当我使用检查元素并尝试提交时,getGames.php 没有出现
标签: javascript php html ajax forms