Jquery/Ajax使用php获取数据库



我有一个HTML页面太大了,无法在这里发布,但我只发布我用来尝试访问PHP文件变量的ajax/jquery。

threadPage.html

<script type="text/javascript">

$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})  
</script>
<!-- bunch of html -->

所以本质上,我试图以JSON形式从ThreadCreation.php中获取变量。它应该在一个数组中,这样我就可以在HTML文件中循环使用它。

ThreadCreation.php

<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);

if (!$conn){
die("unable to connect");
}

$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>

不过,我要重复一遍,这个HTML文件只是通过PHP从数据库中获取信息。所以这里没有表格提交。

我一直觉得"头衔没有定义"。这是有道理的,因为HTML中没有定义标题,但我不确定如何构建ajax请求来收集数据,因为我看到人们只使用这种格式。

首先提到空数组,以防止在没有数据的情况下出错在数据库中,则空数组将继续。

$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);

最新更新