json_encoding一个数组,但作为一个字符串出现

时间:2017-03-26 17:08:15

标签: javascript php arrays json

我试图对一个php文件进行ajax调用,然后创建一个数组,将其编码为json,然后将console.log编入数组中的第一项。目前我在我的主页上有这个:

<script>                

window.setInterval(function ajaxcall(){
            $.ajax({url: "functions/displayPostsDynamic.php",
                success: function(data) 
                {
                console.log(data[0]);
                }
            });
        }, 1000);
</script>                   

所以它每秒都会调用functions / displayPostsDynamic.php,然后在收到数据时输出第一个项目。

这是它调用的php页面:

$result = $stmt->get_result();
$count = mysqli_num_rows($result);
$responseArray = [];

if ($count > 0) //If there is more than one post
{   
    while($row = $result->fetch_assoc()) //For every post, display each one
    { 
        $currentPost[] = ['post_id' => $row["post_id"],'user_id' => $row["user_id"], 'post' => $row["post"], 'date' => $row["date"],'votes_down' => $row["votes_down"],
        'votes_up' => $row["votes_up"]];
    }
    array_push($responseArray, $currentPost);
}   

$stmt->close(); //Close the statment and connection
$conn->close();

echo json_encode(array($responseArray));
?>

所以最重要的是它连接到sql数据库,$ count是表中的多少个。因此,对于每个条目,我想将所有细节添加到数组中,最后,将每个条目推送到一个大数组,以便将其转移回主页。因此,如果我在发送之前打印出responseArray,它将打印出来:

 Array ( 
    [0] => Array ( 
        [0] => Array ( 
            [post_id] => 117 
            [user_id] => 59 
            [post] => lol 
            [date] => 2017-03-26 18:36:21 
            [votes_down] => 2 
            [votes_up] => 1 
        ) 
        [1] => Array ( 
            [post_id] => 104 
            [user_id] => 46 
            [post] => hi from player8 
            [date] => 2017-03-23 22:19:10 
            [votes_down] => 19 
            [votes_up] => 17 
        ) 
    ) 
) 

表中只有2个条目,所以工作得很好。运行时返回主页控制台打印出[作为接收字符串的第一个字符而不是数组的第一个字符。当有人回到主页时,有人会知道如何传输数组甚至将字符串转换为数组吗?谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

在回显前添加此权限:

header('Content-Type: application/json');
echo json_encode($responseArray);

我在您的代码中注意到,如果您想知道您的数据奇怪地填充了深度数组。

$responseArray = []; // initialize array
if ($count > 0) //If there is more than one post
{
    while($row = $result->fetch_assoc()) //For every post, display each one
    {
        $currentPost = ['post_id' => $row["post_id"],'user_id' => $row["user_id"], 'post' => $row["post"], 'date' => $row["date"],'votes_down' => $row["votes_down"],
            'votes_up' => $row["votes_up"]];
        array_push($responseArray, $currentPost); // probably just want to add the post not initialize an array and put the post into that
    }
}

$conn->close();

header('Content-Type: application/json');
echo json_encode($responseArray); // probably dont need that array init here either

答案 1 :(得分:0)

您的数据像字符串一样处理,您只需要在jquery ajax调用中设置数据类型:

$.ajax({
   url: "functions/displayPostsDynamic.php",
   dataType: "json",

或者您可以使用JSON.parse:

success: function(data) 
{
   data = JSON.parse(data);
   console.log(data[0]);
}