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.

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

报告相同问题?

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析