重新加载php页面的一部分而不刷新整个页面

时间:2013-08-20 08:02:30

标签: php javascript ajax wordpress

我使用Wordpress作为内容管理系统,我的模板有一个带box类的div,并包含一个下拉列表。我的目标是使用此值在ajax方法中获取此droplist和查询帖子的值,然后使用ajax重新加载box div,以便在此处获得更清晰的标记:

   <select>

       <option value="1">Item 1</option>

       <option value="2">Item 2</option>

       <option value="3">Item 3</option>

       <option value="4">Item 4</option>

   </select> 

 ------------------
   <div class="content">

     <?php
     $args = array(

        "meta_query" => array(
                array(
                    'key' => 'meta',
                    'value' => '$select_value',
                    )
            )
    );

    query_posts( $args );

      ?> 

      <?php  if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

            <?php the_content(); ?>


      <?php endwhile; else: ?>

             <p>sorry no post found with this value.</p>

      <?php endif; ?>

我认为示例代码很清楚,但我想做这个过程:

用户在dropdown list --> get select value --> put it in $select_value --> run query --> show the div box中选择一个项目而不使用ajax重新加载整个页面...

有人可以帮我写这个吗?

1 个答案:

答案 0 :(得分:1)

   <select id="select-dropdown">
     <option value="1">Item 1</option>
     <option value="2">Item 2</option>
     <option value="3">Item 3</option>
     <option value="4">Item 4</option>
    </select> 

为此,您应该了解wordpress中的Admin Ajax。

管理员Ajax : 在你的  的的header.php

<script type="text/javascript">
 var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>

在自定义js文件中

my-custom.js ,将js文件排入队列

jQuery(document).ready(function(){
  jQuery(body).on('change','#select-dropdown', function(){
     var selected_item  = jQuery(this).val();
     jQuery.ajax({
       type: "POST",
       url: "ajax_url",
       data: {
             action: 'load_posts',
             selected_item: selected_item,
           },
       success: function(res){
         console.log(res);
         //append the result in frontend
         jQuery('.box').html(res);
        },


     })
  })
});

function.php

function _boom_load_posts(){
 //get your results here as per selected option
 if(!empty($_POST['selected_item'])){
  $selected_item = $_POST['selected_item'];
  $output = '';
  //rest of the code as per selected_item, store result in $output
  $args = array(

    "meta_query" => array(
            array(
                'key' => 'meta',
                'value' => '$select_value',
                )
        )
);

query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post();

        $output .= get_the_content();
endwhile; else: 

         $output .= "<p>sorry no post found with this value.</p>"

  endif; 

  echo $output;//you result here
  die(1);
 }
}
add_action('wp_ajax_load_posts', '_dot1_load_posts');
add_action('wp_ajax_no_priv_load_posts', '_dot1_load_posts');

进行必要的更改,因为我无法为您发布整个代码,做出一些努力,上面的代码将帮助您了解它是如何工作的。