在两个不同的页面上加载两个不同的AJAX请求

时间:2019-04-22 作者:user5854648

我让ebeen尝试在不同的页面上调用两个单独的AJAX请求,每个请求都包含各自的部分。现在,它只在两个页面上拉入一个AJAX请求,即使使用特定的IF页面语句,从技术上来说,这些语句应该会阻止它们相互之间的连接。

AJAX可以在调用它的两个页面上工作,但是尽管我付出了努力,两个页面都共享相同的AJAX调用,而不是各自单独的调用。

我怎样才能登上头版。php调用它的特定AJAX调用和类别。php来调用它自己的?现在我有了我觉得应该这样做的代码cat_loadmore_posts 在两页上加载。我试图确保没有共享的函数名,这让它更加好奇为什么要这样做。我很想知道如何做到这一点,但也想知道背后的原因。帮助总是值得感激的。

front-page.php

<?php
$current_page = max( 1, get_query_var( \'paged\' ) );
$the_query = new WP_Query( array(
    \'cat\'            => 5,
    \'post_type\'      => \'post\',
    \'posts_per_page\' => 9,
    \'post_status\' => \'publish\',
    \'paged\'          => $current_page,
) );

$_SESSION[\'count\'] = 1;
wp_localize_script( \'my_loadmore\', \'misha_loadmore_params\', array(
    \'ajaxurl\'      => admin_url( \'admin-ajax.php\', \'relative\' ),
    \'posts\'        => json_encode( $the_query->query_vars ),
    \'current_page\' => $current_page,
    \'max_page\'     => $the_query->max_num_pages
) );
?>

<div id="main" class="container-fluid">
    <?php if ($the_query->have_posts()) : ?>
        <?php $count = 0; ?>
        <?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( \'parts/content\', get_post_format() ); ?>
        <?php $count++; $_SESSION[\'count\']=$_SESSION[\'count\']+1; ?>

<?php if ($count == 8 && is_active_sidebar(\'seriesbar2\') ) : ?>
     <div class="post">
        <?php dynamic_sidebar(\'sidebar\'); ?>
     </div>
<?php endif; ?>

<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
</div><!-- END CONTAINER -->

category.php

<?php
    $current_page = max( 1, get_query_var( \'paged\' ) );
    $cat_query = new WP_Query( array(
        \'posts_per_page\' => 5, 
        \'post_type\'      => \'post\',
        \'category\' => 14, 
        \'post_status\'=>\'publish\',
        \'paged\' => $current_page, 
        \'order\'=>\'DESC\' 
    ) );

    $_SESSION[\'count\'] = 1;
    wp_localize_script( \'cat_loadmore\', \'cat_loadmore_params\', array(
        \'ajaxurl\'      => admin_url( \'admin-ajax.php\', \'relative\' ),
        \'posts\'        => json_encode( $cat_query->query_vars ),
        \'current_page\' => $current_page,
        \'max_page\'     => $cat_query->max_num_pages
    ) );        
?>

<div id="catfeed" class="container feed-container">     
<?php if ($cat_query->have_posts()) : ?>
    <?php $count = 0; ?>
    <?php while ($cat_query->have_posts()) : $cat_query->the_post(); get_template_part( \'parts/categorycontent\', get_post_format() ); ?>
    <?php $count++; $_SESSION[\'count\']=$_SESSION[\'count\']+1; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- END CONTAINER -->
myloadmore.js - the AJAX call that doesn\'t work once I added the catloadmore.js - worked previously

jQuery(function($){
    var canBeLoaded = true,
        bottomOffset = 1300; 

    $(window).scroll(function(){
        if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
            return;
        }
        var data = {
            \'action\': \'loadmore\',
            \'query\': misha_loadmore_params.posts,
            \'page\' : misha_loadmore_params.current_page
        };
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
            $.ajax({
                url : misha_loadmore_params.ajaxurl,
                data: data,
                type: \'POST\',
                beforeSend: function( xhr ){
                    canBeLoaded = false;
                },
                success:function(data){
                    if( data ) {
                        $(\'#main\').find(\'div.post:last-of-type\').after( data );
                        canBeLoaded = true; 
                        misha_loadmore_params.current_page++;
                    }
                }
            });
        }
    });
});

catloadmore.js - This one works on category.php AND front-page.php even though I\'m not calling it on front-page.php. I just want it to work on category.php

jQuery(function($){
    var canBeLoaded = true, 
    bottomOffset = 1300;

    $(window).scroll(function(){
        if ( cat_loadmore_params.current_page >= cat_loadmore_params.max_page ) {     
            return;
        }
        var data = {
            \'action\': \'loadmore\',
            \'query\': cat_loadmore_params.posts,
            \'page\' : cat_loadmore_params.current_page
        };
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){

            $.ajax({
                url : cat_loadmore_params.ajaxurl,
                data: data,
                type: \'POST\',
                beforeSend: function( xhr ){
                    canBeLoaded = false;
                },
                success:function(data){
                    if( data ) {
                        $(\'#catfeed\').find(\'div.catpost:last-of-type\').after( data );
                        canBeLoaded = true;
                        cat_loadmore_params.current_page++;
                    }
                }
            });
        }
    });
});

functions.php

function misha_my_load_more_scripts() {
    if ( is_front_page() )
        {
            wp_register_script( \'my_loadmore\', get_stylesheet_directory_uri() . \'/js/myloadmore.js\',
            array( \'jquery\' ), \'\', true );
            wp_enqueue_script( \'my_loadmore\' );
        }
}
add_action( \'wp_enqueue_scripts\', \'misha_my_load_more_scripts\' );

function cat_load_more_scripts() {
    if ( is_category() )
        {
            wp_register_script( \'cat_loadmore\', get_stylesheet_directory_uri() . \'/js/catloadmore.js\',
            array( \'jquery\' ), \'\', true );
            wp_enqueue_script( \'cat_loadmore\' );
        }
}
add_action( \'wp_enqueue_scripts\', \'cat_load_more_scripts\' );


function register_my_session(){
    if( ! session_id() ) {
        session_start();
    }
}

add_action(\'init\', \'register_my_session\');

function cat_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST[\'query\'] ), true );
    $args[\'paged\'] = $_POST[\'page\'] + 1; // load the next page

    $cat_query = new WP_Query( $args );

    if ( $cat_query->have_posts() ) :

        while ( $cat_query->have_posts() ) : $cat_query->the_post();

            $count = $_SESSION[\'count\'];
            $_SESSION[\'count\']=$_SESSION[\'count\']+1;

            get_template_part( \'parts/categorycontent\', get_post_format() );

        endwhile;
    endif;

    wp_die();
}
add_action( \'wp_ajax_loadmore\', \'cat_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_loadmore\', \'cat_loadmore_ajax_handler\' ); // Non-authenticated users

function misha_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST[\'query\'] ), true );
    $args[\'paged\'] = $_POST[\'page\'] + 1; // load the next page

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :

        while ( $the_query->have_posts() ) : $the_query->the_post();
            $count = $_SESSION[\'count\'];
            $_SESSION[\'count\']=$_SESSION[\'count\']+1;

            get_template_part( \'parts/content\', get_post_format() );

            <?php if ($count == 8 && is_active_sidebar(\'seriesbar2\') ) : ?>
                <div class="series-container post second-series">

                    <?php dynamic_sidebar(\'seriesbar2\'); ?>

                </div>
            <?php endif;
        endwhile;
    endif;

    wp_die();
}
add_action( \'wp_ajax_loadmore\', \'misha_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_loadmore\', \'misha_loadmore_ajax_handler\' ); // Non-authenticated users

UPDATED CODE

Code after @SallyCJ first answer<我代表我疏忽了什么

category.php

<?php
        $current_page = max( 1, get_query_var( \'paged\' ) );
        $category = get_category( get_query_var( \'cat\' ) );
        $cat_id = $category->cat_ID;
        $change = 0;
        $cat_query = new WP_Query( array(
            \'posts_per_page\' => 5, 
            \'post_type\'      => \'post\',
            \'offset\' => 4, 
            \'category__in\' => array($cat_id), 
            \'post_status\'=>\'publish\',
            \'paged\' => $current_page, 
            \'order\'=>\'DESC\' 
    ) );

    $_SESSION[\'count\'] = 1;
    wp_localize_script( \'cat_loadmore\', \'cat_loadmore_params\', array(
        \'ajaxurl\'      => admin_url( \'admin-ajax.php\', \'relative\' ),
        \'posts\'        => json_encode( $cat_query->query_vars ),
        \'current_page\' => $current_page,
        \'max_page\'     => $cat_query->max_num_pages
    ) );        
?>
    <div id="catfeed" class="container-fluid">
            <?php if ($cat_query->have_posts()) : ?>
            <?php $count = 0; ?>
                <?php while ($cat_query->have_posts()) : $cat_query->the_post(); get_template_part( \'parts/categorycontent\', get_post_format() ); ?>
                <?php 
                    $count++;
                    $_SESSION[\'count\']=$_SESSION[\'count\']+1;
                ?>
                <?php endwhile; ?>
            <?php endif; ?>
        <?php wp_reset_postdata(); ?>
    </div><!-- END CONTAINER -->

functions.php

function cat_load_more_scripts() {
    if ( is_category() )
        {
            wp_register_script( \'cat_loadmore\', get_stylesheet_directory_uri() . \'/js/catloadmore.js\',
            array( \'jquery\' ), \'\', true );
            wp_enqueue_script( \'cat_loadmore\' );
        }
}
add_action( \'wp_enqueue_scripts\', \'cat_load_more_scripts\' );

add_action(\'init\', \'register_my_session\');

function cat_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST[\'query\'] ), true );
    $args[\'paged\'] = $_POST[\'page\'] + 1; // load the next page

    $cat_query = new WP_Query( $args );

    if ( $cat_query->have_posts() ) :

        while ( $cat_query->have_posts() ) : $cat_query->the_post();

            $count = $_SESSION[\'count\'];
            $_SESSION[\'count\']=$_SESSION[\'count\']+1;

            get_template_part( \'parts/categorycontent\', get_post_format() );

        endwhile;
    endif;
    wp_die();
}
add_action( \'wp_ajax_catloadmore\', \'cat_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_catloadmore\', \'cat_loadmore_ajax_handler\' ); // Non-authenticated users

function misha_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST[\'query\'] ), true );
    $args[\'paged\'] = $_POST[\'page\'] + 1; // load the next page

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :

        while ( $the_query->have_posts() ) : $the_query->the_post();
            $count = $_SESSION[\'count\'];
            $_SESSION[\'count\']=$_SESSION[\'count\']+1;

            get_template_part( \'parts/content\', get_post_format() );
              if ($count == 4 && is_active_sidebar(\'seriesbar1\') ) : ?>
                <div class="series-container post first-series">

                    <?php dynamic_sidebar(\'seriesbar1\'); ?>

                </div>

            <?php endif; ?>

            <?php if ($count == 8 && is_active_sidebar(\'seriesbar2\') ) : ?>
                <div class="series-container post second-series">

                    <?php dynamic_sidebar(\'seriesbar2\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 12 && is_active_sidebar(\'seriesbar3\') ) : ?>
                <div class="series-container post third-series">

                    <?php dynamic_sidebar(\'seriesbar3\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 16 && is_active_sidebar(\'seriesbar4\') ) : ?>
                <div class="series-container post fourth-series">

                    <?php dynamic_sidebar(\'seriesbar4\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 20 && is_active_sidebar(\'seriesbar5\') ) : ?>
                <div class="series-container post fifth-series">

                    <?php dynamic_sidebar(\'seriesbar5\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 24 && is_active_sidebar(\'seriesbar6\') ) : ?>
                <div class="series-container post sixth-series">

                    <?php dynamic_sidebar(\'seriesbar6\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 28 && is_active_sidebar(\'seriesbar7\') ) : ?>
                <div class="series-container post seventh-series">

                    <?php dynamic_sidebar(\'seriesbar7\'); ?>

                </div>
            <?php endif; ?>

            <?php if ($count == 32 && is_active_sidebar(\'seriesbar8\') ) : ?>
                <div class="series-container post eighth-series">

                    <?php dynamic_sidebar(\'seriesbar8\'); ?>

                </div>
            <?php endif;
        endwhile;
    endif;

    wp_die();
}

add_action( \'wp_ajax_myloadmore\', \'misha_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_myloadmore\', \'misha_loadmore_ajax_handler\' ); // Non-authenticated users

catloadmore.js

jQuery(function($){
var canBeLoaded = true, 
bottomOffset = 1300;

$(window).scroll(function(){
    if ( cat_loadmore_params.current_page >= cat_loadmore_params.max_page ) {     
        return;
    }
    var data = {
        \'action\': \'catloadmore\', // <- same as above action
        \'query\': cat_loadmore_params.posts,
        \'page\' : cat_loadmore_params.current_page
    };
    if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){

        $.ajax({
            url : cat_loadmore_params.ajaxurl,
            data: data,
            type: \'POST\',
            beforeSend: function( xhr ){
                canBeLoaded = false;
            },
            success:function(data){
                if( data ) {
                    $(\'#catfeed\').find(\'div.catpost:last-of-type\').after( data );
                    canBeLoaded = true;
                    cat_loadmore_params.current_page++;
                }
            }
        });
    }
});
});

categorycontent.php - the content being loaded in, truncated for clarity (also just testing this block of code for consistency)

<div class="feed-container row mx-auto align-items-center catpost">  
    <div class="col-sm-5">
        <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( \'thumbnail\', array( \'class\' => \'img-fluid\' ) ); ?></a>
    </div>

    <div class="col-sm-7 mx-auto">
        <h3><a class="align-middle" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    </div>
</div><!-- END ROW -->

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

我很想知道如何做到这一点,但也想知道背后的原因。

我还没有测试你的代码(有条件的东西),但从我所看到的情况来看:

对于首页和类别AJAX请求,AJAX操作的原因是相同的:

  1. myloadmore.js

    var data = {
        \'action\': \'loadmore\', // <- same as below action
        \'query\': misha_loadmore_params.posts,
        \'page\' : misha_loadmore_params.current_page
    };
    
  2. catloadmore.js

    var data = {
        \'action\': \'loadmore\', // <- same as above action
        \'query\': cat_loadmore_params.posts,
        \'page\' : cat_loadmore_params.current_page
    };
    
和infunctions.php, 有两个回调(cat_loadmore_ajax_handlermisha_loadmore_ajax_handler) 连接到名为loadmore. 当在操作所在的位置发出AJAX请求时,将调用这两个回调loadmore, 无论请求来自首页还是类别存档。

但你打电话wp_die() (类似于调用dieexit) 在回调中cat_loadmore_ajax_handler() 调用时,另一个回调将不会运行,因为脚本执行已结束。这就是为什么:

catloadmore.js - This one works on category.php AND front-page.php even though I\'m not calling it on front-page.php.

<“如何”(解决问题)使用不同的操作:

  1. myloadmore.js

    var data = {
        \'action\': \'myloadmore\',
        ...
    };
    
  2. catloadmore.js

    var data = {
        \'action\': \'catloadmore\',
        ...
    };
    
和infunctions.php:

首页:

// AJAX action: myloadmore
add_action( \'wp_ajax_myloadmore\', \'misha_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_myloadmore\', \'misha_loadmore_ajax_handler\' ); // Non-authenticated users

// AJAX action: catloadmore
add_action( \'wp_ajax_catloadmore\', \'cat_loadmore_ajax_handler\' );        // Authenticated users
add_action( \'wp_ajax_nopriv_catloadmore\', \'cat_loadmore_ajax_handler\' ); // Non-authenticated users