我试图从mySQL中获取一个列作为php中的数组,然后使用jquery / ajax将其读入javascript,最后在一些HTML div中显示数组的前四个。
我认为我有php工作,因为当我检查时,我得到一个包含数组中所有元素的返回。
retrieve.php
//Create connection ("Server", "Login name", "Password", "Database name")
$connect = mysql_connect($host, $username , $password);
//Check connection
if (!$connect)
{
die ('could not connect: '. mysql_error());
}
//create connection and select database
mysql_select_db($database, $connect);
//select text column and orders them by most recent postID
$query = "SELECT text FROM $table ORDER BY postID DESC";
$result = mysql_query($query);
//create an array of recent responses
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
mysql_close($connect);
scripting.js
$(document).ready(function(){ //This performs specified actions when the page fully loads
$.ajax({
type: 'POST',
url: 'retrieve.php',
data: 'data',
dataType: 'json',
success: function(result){
$("#box0").html(result[0])
$("#box1").html(result[1])
$("#box2").html(result[2])
$("#box3").html(result[3]);
}
});
答案 0 :(得分:0)
尝试替换
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
与
$rows = array();
while($row = mysql_fetch_array($result)){
$rows[] = $row['text'];
}
echo json_encode($rows);
以json编码行文本数组,而不是单独编码。