jQuery Ajax对wordpress主题的错误请求

时间:2019-07-17 07:59:51

标签: ajax wordpress widget

我创建了一个自定义窗口小部件以显示日历,并且可以在here中找到该日历的代码。

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

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

int16[4]

在上面的类中,我的小部件方法(称为日历)如下所示:

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代码?

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

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

当我查看日历并尝试单击其中一个控件时,我在控制台中看到以下内容:

VM3244:1 POST http://localhost/testtheme/wp-admin/admin-ajax.php 400(错误请求)

编辑:

我的functions.php如下所示:

(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 );

如何使javascript端正常工作?

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

  1. 您永远不会这样设置background: url("../images/chisinau.jpeg") no-repeat; URL。您必须使用script localization

在您的情况下,如果您具有admin-ajax.phpwp_register_script()函数,则还必须使用wp_enqueue_script()

PHP文件

不确定您的脚本句柄是什么,但我将举一个示例:

wp_localize_script()

JS文件

然后在您的JS文件中,使用我们刚刚使用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' ) ) ); 发送的php_obj变量:

wp_localize_script()
  1. 您需要添加WP操作来处理ajax请求。您可以了解更多here

当PHP中没有正确设置ajax操作时,WordPress通常会返回400响应。

作为一个例子。我将提供一个快速示例:

function getCalendar(month,year){
    var url = php_obj.ajaxUrl;
    $.post({
        url,
        data:{
            action: 'calendar_events',
            month: month,
            year: year
        },
        success: function(response){
            $("#calendar-html-output").html(response);  
        },
        error: function(){} 
    });
}

让我知道是否清楚,或者是否需要更多帮助。

这是关于use of AJAX in WP

的另一个很好的参考

编辑

添加代码后,请确保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_enqueue_script()的句柄相同:

wp_localize_script()

编辑2

鉴于WP不允许您通过执行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' ) ) ); } 来实例化窗口小部件这一事实,这意味着您必须将PHPCalendar方法移到另一个类中,然后再在窗口小部件和AJAX调用中实例化。 / p>

这意味着:

CalendarWidget类

$calendar_widget = new __themename_Most_recent_widget();

窗口小部件类文件

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
    }
}

Functions.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');

这应该做:)