我正试图从mySQL中获取一列作为php中的数组,然后用jquery/ajax将其读取到javascript中,最后在一些HTMLdiv中显示数组的前四个。
我想我已经让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]);
}
});
尝试更换
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对行文本数组进行编码,而不是单独对它们进行编码。