繁体   English   中英

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

[英]AJAX request return JSON with properties instead of entire string as one value

我有一个带有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);

}

我想单独访问属性,但是它将“值”作为整个字符串返回,而不是分解为“ content”和“ 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',

不要为每个数组元素调用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>`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM