AJAX-запрос возвращает JSON со свойствами вместо всей строки как одно значение - PullRequest
0 голосов
/ 08 июня 2019

У меня есть запрос AJAX с JSON dataType, показанным здесь:

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',
* * Тысяча двадцать-одина), * * тысяча двадцать две

1 Ответ

1 голос
/ 09 июня 2019

Не вызывайте 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>`);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...