2013-08-20 128 views
0

我使用Wordpress作为内容管理系统,我的模板有一个带box类的div,并且包含一个下拉列表。我的目标是获得与该值AJAX方法本droplist和查询后的值,然后重新用刚刚box DIV阿贾克斯,为获得更清晰这里是标记:重新加载php页面的一部分而不刷新整个页面

<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整个页面...

谁能帮我出书面方式呢?

+0

请点击这里http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/ – elclanrs

+0

问题是什么?你只需要编写jQuery和Ajax和一个PHP函数来给你返回结果 – sven

+0

我已经阅读了一些这样的帖子,不幸的是没有获得成功,你能给我一种方法解决这个问题,用我的代码编写? Thnx为您提供帮助。 –

回答

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知识。

联系阿贾克斯: 在 的header.php

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

自定义的js文件

我-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'); 

进行必要的更改,因为我不能发布给你的整个代码,做一些努力和上面的代码将有助于你得到一个想法,它是如何去工作。

相关问题