AJAX请求返回的JSON具有属性,而不是整个字符串作为一个值

时间:2019-06-08 20:20:13

标签: javascript php jquery json ajax

我有一个带有JSON dataType的AJAX请求,如下所示:

JS:

function checkForNewPosts() {

    var lastCustomerNewsID = <?php echo $customers_news[0]['id']; ?>;

    $.ajax({
        url: "https://www.example.com/check_for_new_posts.php",
        method: "post",
        data:{
            lastCustomerNewsID: lastCustomerNewsID,
        },
        dataType:"json",
        success:function(data)
        {
            $.each(data, function( key, value ) {
                console.log(key + ": " + value);
                $('#wall_posts').prepend(value);
            });
        }
    });

}

PHP:

if ($_POST) {

    $lastCustomerNewsID = $_POST['lastCustomerNewsID'];

    $new_posts = sw::shared()->customers_news->getNewForWall($lastCustomerNewsID);

    if ($new_posts) {

        foreach ($new_posts as $new_post) {

            $content = "<div class='wall_post'>";
            $content .= $new_post['message'];
            $content .= "</div>";

            $last_id = $new_post['id'];

            $testyme[] = json_encode(
                array(
                    "content" => $content,
                    "last_id" => $last_id
                ),
                JSON_UNESCAPED_SLASHES
            );

        }

    }

    echo json_encode($testyme);

}

我想单独访问属性,但它返回的是整个字符串的“值”,而不是分解为“内容”和“ last_id”属性。

示例输出与现有代码:

109: {"content":"<div class='wall_post'></div>","last_id":"367"}
110: {"content":"<div class='wall_post'>testttt</div>","last_id":"366"}

如何返回JSON,以便按属性正确访问?

示例:

 $.each(data.last_id, function( key, value ) {
      $('#wall_posts').prepend(Id: ${value.last_id}, Content: ${value.content}<br>);
 });

JSON输出:

array (
  0 => 
  array (
    'content' => '<div class=\'wall_post\'>Check it out here: <a href=\'https://www.example.com/events/trymeguy/\'>https://www.example.com/events/trymeguy/</a></div>',
'last_id' => '476',

),

1 个答案:

答案 0 :(得分:1)

不要为每个数组元素调用json_encode()。只需编码最终结果即可。因此,循环中的行应为:

            $testyme[] = array(
                "content" => $content,
                "last_id" => $last_id
            );

在处理响应的JS中,您需要提取属性。

$('#wall_posts').prepend(value);

应该是这样的:

$('#wall_posts').prepend(`Id: ${value.last_id}, Content: ${value.content}<br>`);