我正在尝试使用Mysql和Ajax从表中返回数据,但变量中没有任何内容。连接到数据库是好的,查询也可以。
该表包含2个ID,我正在尝试检索它们:
process.php
<script>
function print() {
$.ajax({
url: "process.php",
dataType: 'json',
success : function(data)
{
console.log(data); // OUTPUT
}
});
}
</script>
Ajax功能
Object {current_field: null, field_count: null, lengths: null, num_rows: null, type: null}
输出
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == myModal) {
myModal.style.display = "none";
}
}
答案 0 :(得分:2)
PHP中的$ result变量实际上并没有返回ID,你必须遍历它才能获得如下ID:
<?php
$con = mysqli_connect('localhost','root','root','DBB');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT id FROM events";
$ids = array();
if ($result = mysqli_query($con,$sql)) {
while ($obj = $result->fetch_object()) {
$ids[] = $obj->id;
}
}
echo json_encode($ids);
?>
答案 1 :(得分:1)
你需要遍历每一行:
<?php
$con = mysqli_connect('localhost','root','root','DBB');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT id FROM events";
$rows = array();
if ($result = mysqli_query($con,$sql)) {
while ($row= $result->fetch_array(MYSQL_ASSOC)) {
$rows[] = $row;
}
}
echo json_encode($rows);
$result->close();
$con->close();
?>