如何格式化jSON AJAX请求的PHP查询

时间:2014-01-10 21:23:35

标签: php ajax arrays jquery

我在WordPress中有一个有效的AJAX功能,在那里我循环浏览HTML以获取我的帖子,然后可以在我的AJAX Success CB中访问它们将它们附加到div。

我的问题:

如何在JavaScript中正确使用我的PHP查询功能值(while循环,数组和几个单独的分页值)?

这是我的功能原样;

<?php 
function _custom_paginate(){ 

    $paged = $_POST['count'];
    $args = array(
      'posts_per_page'  => 12,
      'category'        => 3,
      'paged'           => $paged, 
      'post_status'     => 'publish'
    ); 

    $query = new WP_Query($args);
    if ( $query->have_posts() ) :
    while ($query->have_posts()) : $query->the_post(); ?>

      <div class="large-3 three columns box">
        <div class="thumb">
          <?php the_content();?>
          <div class="thumb-foot">
            <div class="thumbinfo">
                <p>Posted on <?php the_time('m.d.Y') ?></p>
            </div>
            <div class="thumb-social">             
              <div class="thumb-twitter"></div>
              <div class="thumb-facebook"></div> 
            </div>
          </div>
        </div>
      </div>
    <?php 
    endwhile;
    endif;

   //Several pagination values
   $total_pages = $query->max_num_pages;
   if ($total_pages > 1){
   $current_page = max(1, get_query_var('paged'));
    ?>
    <div class="pagi-contain">
      <div id="pagi" class="large-12">

        <!-- Append pagination here #pagi-->

        <ul class="pagi">
          <li id="ajaxprev" style="float:left;">prev</li>
          <li id="pagenum"><?php echo $current_page; echo ' ... '.$total_pages; ?></li>
          <li id="total_pages"></li>
          <li id="ajaxnext" style="float:right;">next</li>
        </ul>

      </div>
    </div>
    <?php
}
exit;

}

您不必重写此课程,而是将每个值格式化为可访问的数组(?),以便JS分别处理每个值。我发现this person似乎做了我正在尝试的事情,但这里的主题不是PHP方面......

这是一个希望更清楚我正在努力工作的例子。 http://jsfiddle.net/BenRacicot/LRmc3/

1 个答案:

答案 0 :(得分:2)

我不是100%清楚你想要格式化什么数据,而是这样做:

json_encode($variable_you_want_as_json);

要格式化整个页面的输出,请使用:

ob_start(); // Start output buffering (echos after this go into the buffer, not to the client) 

// all the code and output you want formatted
// example: echo "Some HTML I want to store in a JSON-encoded variable";

$html_data = ob_get_contents(); // Gets the contents of the buffer
ob_end_clean(); // empties the buffer
echo json_encode($html_data); // encodes and echoes whatever you did between ob_start() and ob_get_contents()

听起来你想要多个值,所以你可以用数组替换最后一行中的变量,如下所示:

$my_array = array('html_data'=>$html_data,
    'max_num_pages' => $query->max_num_pages,
    'foo'=>$foo,
    'bar'=>$bar,
    'some_other_var' => $some_other_var);
echo json_encode($my_array);