我所有的SQL代码和东西都能工作,就像我说的,如果
$jTableResult = array();
$jTableResult['message'] = $rows1;
echo json_encode($jTableResult);
是
$jTableResult = array($rows1);
echo json_encode($jTableResult);
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#alertbut").click(function(){
$.ajax({
type: 'POST',
url: '../ajax/ajax.php?key=8789789fdgjhl',
//data:dataString,
dataType: 'json',
success: function (s) {
//alert(s);
$( "#alerts" ).empty();
$('#alerts').append($.parseJSON(s[0]));
}
});
});
});
PHP:
if($key == "8789789fdgjhl")
{
$getalerts = $odb->prepare("SELECT * FROM alerts LIMIT 5");
$getalerts->execute();
$rows = array();
while($row = $getalerts->fetch(PDO::FETCH_ASSOC))
{
$rows1[] = $row['user'];
}
$jTableResult = array();
$jTableResult['message'] = $rows1;
echo json_encode($jTableResult);
}
当您将JSON接收到success
函数时,JSON已经被解析,因为您已经告诉ajax调用期望的dataType是json
。因此,$.parseJSON()
将把你的对象变成一个个个位数的字符串,比如[object Object]
,所以在你的例子中你会得到o
。
改变它。
$('#alerts').append(s[0]);
如果返回的数组具有索引为0的数组的关键字s
,则应该会给出您所期望的结果。
编辑
给定您提供的链接,实际上您有一个数组,该数组在message
的索引处包含一组名称。请使用以下内容:
$('alerts').append(s.message[0]);