如何使Ajax在WordPress中返回HTML?

时间:2019-01-30 08:38:12

标签: javascript php jquery ajax wordpress

我的.php文件中有此HTML

<div id="orderby">
  <a href="" data-orderby="date" class="active">Date</a>
  <a href="" data-orderby="title">Alphabetical order</a>
</div>
<ul>
  <li><!-- Listing of a post --></li>
  <li><!-- Listing of a post --></li>
  <li><!-- Listing of a post --></li>
  ...
</ul>

我的.js文件中有用于事件监听器的js:

$('#orderby a').on('click', function(){
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    getProjects();

    return false;
});

我在同一文件中有这个用于ajax的文件:

function getProjects(){
    var orderby = $('#orderby a.active').attr('data-orderby'),
      projectsListing = $('ul');

    $projectsListing.animate({opacity: 0}, 450, function(){
        $.ajax({
            cache: false,
            timeout: 8000,
            url: php_array.admin_ajax, //see functions.php
            type: "POST",
            // response: 'ajax-response',
            dataType: "html",
            data: ({ action:'get_filtered_projects', order: orderby, filter: filterby }),
            success: function(data){
                alert( data ); //blank [![all post <li> items between the filter and the footer are gone][1]][1]
                $projectsListing.html(data);
                $toLoad = $('.to-load');
                $projectsListing.css({'opacity': 1});
                positionContent();
            },
            error: function(data) {
                alert('fail');
            }
        });
    });
}

positionContent() {...}

这是我的functions.php文件:

function enqueue_stuff() { 

    wp_enqueue_script( 'plugins', get_template_directory_uri() . '/javascript/plugins.js', array( 'jquery', 'jquery-ui-core', 'jquery-ui-widget' ), '1.0.0', true );
    wp_enqueue_script( 'ui'       , get_template_directory_uri() . '/javascript/ui.js'     , array( 'plugins', 'wp-ajax-response' )                           , '1.0.1', true );

    wp_localize_script( 'ui', 'php_array', array( 'admin_ajax' => admin_url('admin-ajax.php') ) );
}
add_action('wp_enqueue_scripts', 'enqueue_stuff');

add_action('wp_ajax_get_filtered_projects', 'get_filtered_projects' );
add_action('wp_ajax_nopriv_get_filtered_projects', 'get_filtered_projects' );
function get_filtered_projects() {
  if (isset($_POST['action'])) {
        console.log('isset');
        $orderby = $_POST['order']; 
        $filterby = $_POST['filter'];
        $args = array(
            'post_type' => 'projects',
            'posts_per_page' => -1, 
            'orderby' => $orderby,
        ); 
  }
  $the_query = new WP_Query( $args );
  if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post(); 
      // loop stuff and echo everything inside 
    endwhile;
  wp_reset_postdata();
  endif;
  die('');

}

警报仍然返回空白,并且前端屏幕没有任何返回。 感谢您抽出宝贵的时间。

0 个答案:

没有答案