json值不断返回unidentified或根本不显示
PHP代码
$index=0;
while($row = $result->fetch_array()){
$index++;
$data=array(
array(
$index=>$row['menuName']
)
);
}
echo json_encode($data);
}
JQUERY AJAX
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
$('.navbar ul').append('<li><a href="#" class="table">'+data[0]+'</a></li>');
}
}); //ajax request
});
</script>
json很好,它以正确的格式显示。当我将jquery更改为data [0]时,它将显示对象Object;如果我执行data [1或更高版本],它将给我未定义的信息。我不知道我在做什么错,我什至尝试过这样做:data [0] .1,它什么也不显示。
任何帮助将不胜感激。
首先要做的是修复响应该请求的PHP脚本部分。
创建有效的JSON字符串响应。最简单的方法是首先创建一个容器(数组)。
第二个是继续将提取的行推入那里。然后最终使用json_encode
到最后。
不要在循环内进行编码:
简单的例子:
// initialize container
$data = array();
// the pushing of rows
while($row = $result->fetch_array()) {
$data[] = $row; // push the whole row
}
// finally, echo it to into a JSON string
echo json_encode($data);
// don't put me inside the WHILE
PHP注意:如果是mysqli
,则建议使用->fetch_assoc()
代替或只是简单地使用->fetch_array(MYSQLI_ASSOC)
flag。
在您的AJAX脚本中,只需按照通常的方式处理响应:
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
data: {loadpage: 'table'},
dataType: 'json',
url: 'addtable.php',
success: function(data){
// every each row, create an LI element with an anchor
$.each(data, function(index, element){
$('.navbar ul').append('<li><a href="#" class="table">'+element.menuName+'</a></li>');
// just use the column names as the properties in your data response that came from PHP
});
}
});
});
</script>
如果运行了,这应该会在标记中产生一些效果,如下所示:
<li>
<a href="#" class="table">Table1</a>
</li>
<li>
<a href="#" class="table">Table2</a>
</li>
<li>
<a href="#" class="table">Table4</a>
</li>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句