【发布时间】:2023-03-30 18:17:01
【问题描述】:
我做了一个简单的应用程序 php & ajax,但我不知道为什么它不起作用。
我的代码:
<?php
$grId = $_GET["groupId"];
$limit = $_GET["limit"];
if ($limit <= 0) {
$limit = 10;
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "productsdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $grId, $limit);
$stmt->execute();
$stmt->bind_result($id, $displayName, $role, $groupId);
$users = array();
while($stmt->fetch()) {
$user = new StdClass();
$user->id = $id;
$user->displayName = $displayName;
$user->role = $role;
$user->groupId = $groupId;
array_push($users, $user);
}
echo json_encode($users);
$stmt->close();
$conn->close();
?>
json-client-get.html:
<html>
<head>
<script src="jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$('#students').hide();
$("#getStudentsButton").click(function() {
$.ajax({
dataType: "json",
type: "GET",
url: "getStudentsJson.php",
data: {
groupId: 1,
limit: 7
},
success: renderTable
});
});
function renderTable(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.displayName + '</td><td>' + item.role + '</td> <td> ' + item.groupId + ' </td></tr>';
});
$('#students').append(trHTML);
$('#students').show();
}
});
</script>
</head>
<body>
Lista studentilor din grupul 1:
<div id="maindiv">
<table id="students" border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Role</th>
<th>GroupId</th>
</tr>
</table>
</div>
<input id="getStudentsButton" type="button" value="Load students" />
</body>
</html>
我在 phpmyadmin 中创建了一个新的数据库 productsdb,其中包含表用户和插入的单个值。
当我运行 localhost/folder/json-client-get.html 并按下按钮加载学生时,什么都没有发生。
编辑(与我的数据库合影,但我不知道为什么照片不起作用)
【问题讨论】:
-
成功后进入renderTable()函数??你有没有在这个函数中通过警报检查过?
-
从你的
while循环中取出这个 ->$user = new StdClass(); -
console.log(data)在readerTable函数中。 -
你
success: renderTable行应该是成功的:function(){//renderTable} -
@Hirdesh Vishwdewa 没有任何变化
标签: php jquery mysql json ajax