关于wordpress主题的JQuery Ajax错误请求

关于wordpress主题的JQuery Ajax错误请求,ajax,wordpress,widget,Ajax,Wordpress,Widget,我创建了一个自定义小部件来显示日历,可以找到日历的代码 从我的主题根目录中,文件夹结构如下所示: inc/most-recent-widget.php 所有日历代码都已添加到小部件类中: class __themename_Most_recent_widget extends WP_Widget{ private $weekDayName = array ("MON","TUE","WED","THU","FRI","SAT","SUN"); private $currentD

我创建了一个自定义小部件来显示日历,可以找到日历的代码

从我的主题根目录中,文件夹结构如下所示: inc/most-recent-widget.php

所有日历代码都已添加到小部件类中:

class __themename_Most_recent_widget extends WP_Widget{

    private $weekDayName = array ("MON","TUE","WED","THU","FRI","SAT","SUN");
    private $currentDay = 0;
    private $currentMonth = 0;
    private $currentYear = 0;
    private $currentMonthStart = null;
    private $currentMonthDaysLength = null; 

    function __construct() {
        parent::__construct(
            '_themename_most_recent_widget',
            esc_html__('Recent Posts', '_themename'),
            ['description' => esc_html__('some description', '_themename')]
        );
        $this->currentYear = date ( "Y", time () );
        $this->currentMonth = date ( "m", time () );

        if (! empty ( $_POST ['year'] )) {
            $this->currentYear = $_POST ['year'];
        }
        if (! empty ( $_POST ['month'] )) {
            $this->currentMonth = $_POST ['month'];
        }
        $this->currentMonthStart = $this->currentYear . '-' . $this->currentMonth . '-01';
        $this->currentMonthDaysLength = date ( 't', strtotime ( $this->currentMonthStart ) );
    }

    function getCalendarHTML() {
        $calendarHTML = '<div id="calendar-outer">'; 
        $calendarHTML .= '<div class="calendar-nav">' . $this->getCalendarNavigation() . '</div>'; 
        $calendarHTML .= '<ul class="week-name-title">' . $this->getWeekDayName () . '</ul>';
        $calendarHTML .= '<ul class="week-day-cell">' . $this->getWeekDays () . '</ul>';        
        $calendarHTML .= '</div>';
        return $calendarHTML;
    }

    function getCalendarNavigation() {
        $prevMonthYear = date ( 'm,Y', strtotime ( $this->currentMonthStart. ' -1 Month'  ) );
        $prevMonthYearArray = explode(",",$prevMonthYear);

        $nextMonthYear = date ( 'm,Y', strtotime ( $this->currentMonthStart . ' +1 Month'  ) );
        $nextMonthYearArray = explode(",",$nextMonthYear);

        $navigationHTML = '<div class="prev" data-prev-month="' . $prevMonthYearArray[0] . '" data-prev-year = "' . $prevMonthYearArray[1]. '"><</div>'; 
        $navigationHTML .= '<span id="currentMonth">' . date ( 'M ', strtotime ( $this->currentMonthStart ) ) . '</span>';
        $navigationHTML .= '<span contenteditable="true" id="currentYear">'.    date ( 'Y', strtotime ( $this->currentMonthStart ) ) . '</span>';
        $navigationHTML .= '<div class="next" data-next-month="' . $nextMonthYearArray[0] . '" data-next-year = "' . $nextMonthYearArray[1]. '">></div>';
        return $navigationHTML;
    }

    function getWeekDayName() {
        $WeekDayName= '';       
        foreach ( $this->weekDayName as $dayname ) {            
            $WeekDayName.= '<li>' . $dayname . '</li>';
        }       
        return $WeekDayName;
    }

    function getWeekDays() {
        $weekLength = $this->getWeekLengthByMonth ();
        $firstDayOfTheWeek = date ( 'N', strtotime ( $this->currentMonthStart ) );
        $weekDays = "";
        for($i = 0; $i < $weekLength; $i ++) {
            for($j = 1; $j <= 7; $j ++) {
                $cellIndex = $i * 7 + $j;
                $cellValue = null;
                if ($cellIndex == $firstDayOfTheWeek) {
                    $this->currentDay = 1;
                }
                if (! empty ( $this->currentDay ) && $this->currentDay <= $this->currentMonthDaysLength) {
                    $cellValue = $this->currentDay;
                    $this->currentDay ++;
                }
                $weekDays .= '<li>' . $cellValue . '</li>';
            }
        }
        return $weekDays;
    }

    function getWeekLengthByMonth() {
        $weekLength =  intval ( $this->currentMonthDaysLength / 7 );    
        if($this->currentMonthDaysLength % 7 > 0) {
            $weekLength++;
        }
        $monthStartDay= date ( 'N', strtotime ( $this->currentMonthStart) );        
        $monthEndingDay= date ( 'N', strtotime ( $this->currentYear . '-' . $this->currentMonth . '-' . $this->currentMonthDaysLength) );
        if ($monthEndingDay < $monthStartDay) {         
            $weekLength++;
        }

        return $weekLength;
    }

    public function widget($args, $instance){
        echo $this->getCalendarHTML();
    }


}

function __themename_register_most_recent_widget(){
    register_widget('__themename_Most_recent_widget');
}

add_action('widgets_init', '__themename_register_most_recent_widget');
在此之前,日历将显示其样式。 如何运行Javascript和Ajax代码

我创建了一个名为customize-controls.js的js文件:

(function( $ ) {
    $(document).ready(function(){

        $(document).on("click", '.prev', function(event) { 
            var month =  $(this).data("prev-month");
            var year =  $(this).data("prev-year");
            getCalendar(month,year);
        });

        $(document).on("click", '.next', function(event) { 
            var month =  $(this).data("next-month");
            var year =  $(this).data("next-year");
            getCalendar(month,year);
        });
        $(document).on("blur", '#currentYear', function(event) { 
            var month =  $('#currentMonth').text();
            var year = $('#currentYear').text();
            getCalendar(month,year);
        });
    });

    function getCalendar(month,year){
        var url = "/testtheme/wp-admin/admin-ajax.php";
        $.ajax({
            url: url,
            action : 'calendar_events',
            type: "POST",
            data:'month='+month+'&year='+year,
            success: function(response){
                $("#calendar-html-output").html(response);  
            },
            error: function(){} 
        });
    }
})( jQuery );
当我查看日历并尝试单击其中一个控件时,我会在控制台中看到以下内容:

VM3244:1 POST 400(错误请求)

编辑:

My functions.php如下所示:

function twentynineteen_scripts() {
    wp_enqueue_style( 'twentynineteen-style', get_stylesheet_uri(), array(), wp_get_theme()->get( 'Version' ) );


    wp_enqueue_script( 'twentynineteen-customControl', get_theme_file_uri( '/js/customize-controls.js' ), array('jquery'), '1.1', true );

    wp_localize_script( 'customize-controls-script', 'php_obj',
        array(
            'ajaxUrl' => admin_url( 'admin-ajax.php' )
        )
    );
}
add_action( 'wp_enqueue_scripts', 'twentynineteen_scripts' );

add_action( 'wp_ajax_calendar_events', 'calendar_events_callback' );
add_action( 'wp_ajax_nopriv_calendar_events', 'calendar_events_callback' );
function calendar_events_callback() {

    exit();
}

如何让javascript端正常工作?

您的代码存在一些问题

  • 您从未这样设置过
    admin ajax.php
    URL。您必须使用:
  • 在您的情况下,如果有
    wp\u register\u script()
    wp\u enqueue\u script()
    函数,您还必须使用
    wp\u localize\u script()

    PHP文件

    class __themename_Most_recent_widget extends WP_Widget{
    
        function __construct() {
            parent::__construct(
                '_themename_most_recent_widget',
                esc_html__('Recent Posts', '_themename'),
                ['description' => esc_html__('some description', '_themename')]
            );
        }
    
        public function widget($args, $instance){
            $phpCalendar = new CalendarWidget();
    
            $calendarHTML = $phpCalendar->getCalendarHTML();
            echo $calendarHTML;
        }
    
    
    }
    
    function __themename_register_most_recent_widget(){
        register_widget('__themename_Most_recent_widget');
    }
    
    add_action('widgets_init', '__themename_register_most_recent_widget');
    
    不确定您的脚本句柄是什么,但我将给出一个示例:

    wp_enqueue_script('customize-controls-script', get_stylesheet_directory_uri() . 'customize-controls.js');
    
    wp_localize_script( 'customize-controls-script', 'php_obj',
        array(
            'ajaxUrl' => admin_url( 'admin-ajax.php' )
        )
    );
    
    JS文件

    class __themename_Most_recent_widget extends WP_Widget{
    
        function __construct() {
            parent::__construct(
                '_themename_most_recent_widget',
                esc_html__('Recent Posts', '_themename'),
                ['description' => esc_html__('some description', '_themename')]
            );
        }
    
        public function widget($args, $instance){
            $phpCalendar = new CalendarWidget();
    
            $calendarHTML = $phpCalendar->getCalendarHTML();
            echo $calendarHTML;
        }
    
    
    }
    
    function __themename_register_most_recent_widget(){
        register_widget('__themename_Most_recent_widget');
    }
    
    add_action('widgets_init', '__themename_register_most_recent_widget');
    
    然后在JS文件中使用我们刚才使用
    wp\u localize\u script()发送的
    php\u obj
    变量:

  • 您需要添加WP操作来处理ajax请求。你可以学到更多
  • 当PHP中没有正确设置ajax操作时,WordPress通常会返回400响应

    举个例子。我将写下一个快速样本:

    add_action( 'wp_ajax_calendar_events', 'calendar_events_callback' );
    add_action( 'wp_ajax_nopriv_calendar_events', 'calendar_events_callback' );
    function calendar_events_callback() {
    
        // logic for the output
    
        // here you output the html you need to the calendar
    
        // make sure you exit so the output stops when the request is done
        exit();
    }
    
    让我知道这是否清楚,或者你是否需要更多的帮助

    这里是另一个关于

    编辑

    添加代码后,确保
    wp\u enqueue\u script()
    的句柄与
    wp\u localize\u script()
    的句柄相同:

    function twentynineteen_scripts() {
        wp_enqueue_style( 'twentynineteen-style', get_stylesheet_uri(), array(), wp_get_theme()->get( 'Version' ) );
    
    
        wp_enqueue_script( 'twentynineteen-customControl', get_theme_file_uri( '/js/customize-controls.js' ), array('jquery'), '1.1', true );
    
        wp_localize_script( 'twentynineteen-customControl', 'php_obj',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' )
            )
        );
    }
    
    编辑2

    鉴于WP不允许您通过执行
    $calendar\u widget=new\uuu themename\u Most\u recent\u widget()来实例化小部件,意味着您必须将PHPCalendar方法移动到另一个类中,然后在小部件和AJAX调用中实例化该类

    这意味着:

    CalendarWidget类

    class CalendarWidget{
        private $weekDayName = array ("MON","TUE","WED","THU","FRI","SAT","SUN");
        private $currentDay = 0;
        private $currentMonth = 0;
        private $currentYear = 0;
        private $currentMonthStart = null;
        private $currentMonthDaysLength = null;
    
        function __construct() {
    
            //method here
        }
    
        function getCalendarHTML() {
            //method here
        }
    
        function getCalendarNavigation() {
            //method here
        }
    
        function getWeekDayName() {
            //method here
        }
    
        function getWeekDays() {
            //method here
        }
    
        function getWeekLengthByMonth() {
            //method here
        }
    }
    
    小部件类文件

    class __themename_Most_recent_widget extends WP_Widget{
    
        function __construct() {
            parent::__construct(
                '_themename_most_recent_widget',
                esc_html__('Recent Posts', '_themename'),
                ['description' => esc_html__('some description', '_themename')]
            );
        }
    
        public function widget($args, $instance){
            $phpCalendar = new CalendarWidget();
    
            $calendarHTML = $phpCalendar->getCalendarHTML();
            echo $calendarHTML;
        }
    
    
    }
    
    function __themename_register_most_recent_widget(){
        register_widget('__themename_Most_recent_widget');
    }
    
    add_action('widgets_init', '__themename_register_most_recent_widget');
    
    Functions.php

    function twentynineteen_scripts() {
        wp_enqueue_style( 'twentynineteen-style', get_stylesheet_uri(), array(), wp_get_theme()->get( 'Version' ) );
    
    
        wp_enqueue_script( 'twentynineteen-customControl', get_theme_file_uri( '/js/customize-controls.js' ), array('jquery'), '1.1', true );
    
        wp_localize_script( 'twentynineteen-customControl', 'php_obj',
            array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' )
            )
        );
    }
    
    add_action( 'wp_enqueue_scripts', 'twentynineteen_scripts' );
    
    add_action( 'wp_ajax_calendar_events', 'calendar_events_callback' );
    add_action( 'wp_ajax_nopriv_calendar_events', 'calendar_events_callback' );
    
    function calendar_events_callback() {
    
        $phpCalendar = new CalendarWidget();
    
        $calendarHTML = $phpCalendar->getCalendarHTML();
        echo $calendarHTML;
        exit();
    
    }
    

    这应该可以做到:)

    确保还附加了AJAX的PHP代码action@cornel.raiu我不想在这个问题上说太多,因此我引用了PhP的源代码。但我只是更新了我的答案。现在写一个答案我只是通过添加排队脚本代码来编辑我的问题。看看我的ajax代码,什么是正确的“操作”。还有,我如何在你创建的“calendar\u events\u callback”函数中调用日历的html?我将我的js更改为与你答案中的js完全相同,但仍然看到错误的请求错误,现在使用changesLet us更新答案。非常感谢支持