doufan9377 2014-10-10 11:00
浏览 45
已采纳

wordpress ajax和foreach - 不返回数组

last time I fight with Ajax and WordPress. I have a problem using Ajax wants to load the Posts of the same category ... in response is replaced Object, only one entry.

Where to find the problem?

ajax.js

var $fnWritePostGrid = function (idCat) {
        var data = {
            type: 'POST',
            url: ajaxOptions.url,
            action: 'kk_load_servicesGrid',
            idCat: idCat
        };
        $.ajax({
            type: "POST",
            url: ajaxOptions.url,
            data: data,
            dataType: "json",
            success: function (response) {
                console.log(response);
            }

        });
        return false;

    };

functions.php

$cat_id = $_POST['idCat'];
$args = array(
    'category' => $cat_id,
    'posts_per_page' => 8,
    'order' => 'DESC'
);  

$posts = get_posts($args);

foreach($posts as $post) {
    $postID = sanitize_text_field($post->ID);
    $postTitle = sanitize_text_field($post->post_title);
    $postContent = sanitize_text_field($post->post_content);

    $response = array(
        'ID' => $postID,
        'title' => $postTitle,
        'content' => $postContent
    );
    echo json_encode($response);
    exit;
}

In summary, the code works but doesn't return an array of entries, only the first entry in the category.

Please help and thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanchi0897 2014-10-10 11:08
    关注

    It looks as though your PHP is exiting the thread after the first iteration of your foreach loop:

    echo json_encode($response);
    exit;
    

    What you likely want to do instead is create an array of all of the posts that you want to return -- something like this:

    $responses = array();
    
    foreach($posts as $post) {
        $postID = sanitize_text_field($post->ID);
        $postTitle = sanitize_text_field($post->post_title);
        $postContent = sanitize_text_field($post->post_content);
    
        $response = array(
            'ID' => $postID,
            'title' => $postTitle,
            'content' => $postContent
        );
        array_push($responses, $response)
    }
    
    echo json_encode($responses);
    exit;
    

    This way you'll actually be returning a JSON array of objects, rather than a single JSON object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?