我仅在此处发布相关代码。我正在尝试访问json数组中的数组。如何访问数组中的数组?
所以这是服务器端代码:
$scriptfull = array();
while($r = mysqli_fetch_assoc($resultstmt_scriptfull)) {
$scriptfull[] = $r;
}
$resulterr = array('message' => 'Success',
'fullscript'=>$scriptfull);
header('Content-Type: application/json');
echo json_encode($resulterr);
我知道如何使用Javascript访问JSON数组。我不知道如何访问基本对象,该对象本身就是JSON数组中的数组。
当我这样做时:
success: function(output)
{
console.log(output.fullscript);
}
我在控制台中看到结果
(1)[...]
0:{...}
scriptAA1: "a1"
scriptAA10: "a10"
scriptAA2: "a2"
scriptAA3: "a3"
但是如果我尝试的话,HTML上什么也不会打印
success: function(output)
{
$('.scriptview').html(output.fullscript);
}
我尝试使用以下代码访问它,但未打印任何内容:
success: function(output)
{
$('.scriptview').html(output.fullscript[1]);
}
答案 0 :(得分:1)
您正在做的是尝试在html上打印对象的javascript数组,这当然没有意义,并且为什么不打印任何内容。您可以像这样将javascript数组打印为字符串(可能不是您想要的):
$('.scriptview').html(JSON.stringify(output.fullscript));
我认为您应该更好地解释您试图打印到html的确切内容。
编辑: 据我了解,您需要类似控制台中的内容。对于这样的事情,下面的代码可以做到:
var outputString = '';
output.fullscript.forEach(function(object, index){
outputString += '<br> Object with index: ' + index + '<br>';
for (var prop in object){
outputString += 'Property ' + prop + ': ' + object[prop] + '<br>';
}
});
$('.scriptview').html(outputString);
答案 1 :(得分:1)
由于您尝试将结果输出为字符串,因此可以使用
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript));
}
如果您要使用空格格式化结果,则stringify
方法的第3个参数将执行以下操作:
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript, null, '\t'));
}
更短,更易读,更有效的方法是仅使用jQuery text
方法而不是html
进行显示:
success: function(output)
{
$('.scriptview').text(JSON.stringify(output.fullscript, null, '\t'));
}
这看起来更整洁...