用AJAX实现页眉背景图像的检索

时间:2017-03-02 作者:LebCit

“我的主题”中的特色图像(用于帖子和页面)是标题背景图像
实际上,每个特征图像都由以下内容检索function 在里面functions.php :

function mytheme_header_style() {
    // Declare $post global if used outside of the loop.
    $post = get_post();
    // Check if post is object otherwise we\'re not in singular post.
    if (!is_object($post)) {
        return;
    }
    // If Object
    $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), \'\');
    // Add inline style to the backgroung header image.
    if (has_post_thumbnail()) {
        $custom_header_style = \'
            .intro-header {
                background-image: url( \' . $backgroundImg[0] . \' );
            }
        \';
    } else {
        $custom_header_style = \'
            .intro-header {
                background-image: url( \' . get_template_directory_uri() . \'/components/header/images/default-hero.jpg\' . \' );
            }
        \';
    }
    wp_add_inline_style( \'mytheme-main-style\', $custom_header_style );
}
add_action( \'wp_enqueue_scripts\', \'mytheme_header_style\' );
此背景图像由jQuery function 在单独的hero.js 文件在任何设备上始终全屏显示/屏幕大小如下:

jQuery(document).ready(function ($) {
    // Defining a function to set size for #masthead 
    function fullscreen() {
        jQuery(\'#masthead\').css({
            width: jQuery(window).width(),
            height: jQuery(window).height()
        });
    }

    fullscreen();

    // Run the function in case of window resize
    jQuery(window).resize(function () {
        fullscreen();
    });

});
TheHTML 的结构header.php 使此特色背景标题图像与主要内容分离,如下所示:

<body>
  <div id="page">
    <nav>...</nav>
     <!-- Page Header -->
     <?php
     if (is_404()) {
         get_template_part(\'components/header/bg\', \'404\');
     } elseif (is_search()) {
         get_template_part(\'components/header/bg\', \'search\');
     } else {
         get_template_part(\'components/header/bg\', \'header\'); // mytheme_header_style() is called here
     }
     ?>
    <!-- Main Content -->
    <div id="content">...</div>
  </div>//#page
  <footer>...</footer>
</body>
I\'m trying the following
1- 本地化hero.js

function mytheme_header_style_script() {

        // Adding custom javascript header style file to theme.
        wp_enqueue_script(\'mytheme-hero\', get_theme_file_uri() . \'/assets/js/hero.js\', array(\'jquery\'));
        wp_localize_script(\'mytheme-hero\', \'hero_ajax\', array(\'ajaxurl\' => admin_url( \'admin-ajax.php\' )));

}
add_action(\'wp_enqueue_scripts\', \'mytheme_header_style_script\');
2- 将wp\\U ajax操作添加到mytheme_header_style() 作用

add_action( \'wp_enqueue_scripts\', \'mytheme_header_style\' );
add_action(\'wp_ajax_heroajax\', \'mytheme_header_style\');
add_action(\'wp_ajax_nopriv_heroajax\', \'mytheme_header_style\');
3- 然后我改变了hero.js 像这样:

jQuery(document).ready(function() {
  // Handler for .ready() called.
    $.ajax({
        type: "post",
        url: hero_ajax.ajaxurl,
        data: {
            action : \'heroajax\'
        },
        // callback handler that will be called on success
        // Defining a function to set size for #masthead
        success: function fullscreen(imageUrl, textStatus, jqXHR){
            // log a message to the console
            console.log("Hooray, it worked! Load The Image Here");
                $(\'#masthead\').css({
                    width: $(window).width(),
                    height: $(window).height()
                });
                $(\'#masthead\').css(\'background-image\', \'url(\' + DefaultimageUrl + \')\');
        },
        // callback handler that will be called on error
        error: function(jqXHR, textStatus, errorThrown){
            DefaultimageUrl = \'path/to/default/image.jpg\';                        
            // log the error to the console
            console.log(
                "Load Default Image here! The following error occured: "+
                textStatus, errorThrown
            );
            $(\'#masthead\').css(\'background-image\', \'url(\' + DefaultimageUrl + \')\');
        }
    });

    fullscreen();

    // Run the function in case of window resize
    $(window).resize(function () {
        fullscreen();
    });

});
这不起作用,特色的背景标题图像不再是全屏,JS调试器正在高亮显示$.ajax 并且说Paused on Exception 我在控制台里没有收到任何消息<我做错了什么?非常感谢您的帮助,提前谢谢大家。

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

这比我想象的要容易<经过大量的阅读和尝试,我终于明白了<这是一个答案,如果它能帮助某人,请加以说明
1- 在里面functions.php 本地化hero.js

function mytheme_header_script() {

    // Adding custom javascript file to handle the header image.
    wp_enqueue_script(\'mytheme-hero\', get_theme_file_uri() . \'/assets/js/hero.js\', array(\'jquery\'), \'\', true); // I\'m putting the script in the footer

    // Declare $post global if used outside of the loop.
    $post = get_post();

    // Retrieve the featured image by using wp_get_attachment_image_src
    // and include the id of the post as a parameter for get_post_thumbnail_id (which we retrieve using $post->id)
    $heroImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), \'\');

    // This is an array of values that we will use each by it\'s key in hero.js script file
    $heroSettings = array (
        \'featured_image\'     => $heroImg[0], // Retrieve the featured image and display it if set
        \'default_image\'      => get_template_directory_uri() . \'/components/header/images/default-hero.jpg\', // Display the default image if no featured image is set
        \'has_post_thumbnail\' => has_post_thumbnail(), // To use the function in js
        \'ajaxurl\'            => admin_url( \'admin-ajax.php\' ), // The URL to admin-ajax.php
        \'success\'            => \'Hooray, it worked! The featured image is loaded\', // Print this message in the console if the featured image is displayed
        \'default\'            => \'The default image is loaded\' // Print this message in the console if the default image is displayed
    );
    // Now use the wp_localize_script function
    // Set the same $handle as the script to localize it
    // hero-set is the name of the js variable that will contain the data
    // $heroSettings is the array of data to retrieve in js by hero_set
    wp_localize_script(\'mytheme-hero\', \'hero_set\', $heroSettings);
}
add_action(\'wp_enqueue_scripts\', \'mytheme_header_script\');
2- 还是一样:)

3- hero.js 变成了这样

(function($) {

    // Define the fullscreen function
    fullscreen();

    // Tell the fullscreen function what to do using ajax
    function fullscreen() {
        $.ajax({
            type: \'POST\', // use $_POST method to submit the data
            url: hero_set.ajaxurl, // submit the data to admin-ajax.php
            data: {
                action : \'mytheme_header_style\'
                // process mytheme_header_style function by the requested data action
            },
            // use beforeSend so the background header image is retrieved and displayed
            // wright away before anything else to speed the page load
            beforeSend : function(){
                // if a featured image is set
                if (hero_set.has_post_thumbnail){
                    // log the success message to the console
                    console.log(hero_set.success);
                    $(\'#masthead\').css({
                        \'background-image\': \'url(\' + hero_set.featured_image + \')\',
                        width: $(window).width(),
                        height: $(window).height()
                    });
                } else {
                    // if no featured image is set
                    // log the default message to the console
                    console.log(hero_set.default);
                    $(\'#masthead\').css({
                        \'background-image\': \'url(\' + hero_set.default_image + \')\',
                        width: $(window).width(),
                        height: $(window).height()
                    });
                }
            }
        });
    }

    // Run the function in case of window resize.
    $(window).resize(function(e) {
        e.preventDefault();
        fullscreen();
    });
})(jQuery);
这就是所有的人,希望它能帮助别人
SYA

相关推荐

WordPress AJAX错误400向远程站点发送数据的错误请求

我正在使用发件人。net获取电子邮件订阅列表。这个网站给了我一些信息,可以将用户的电子邮件添加到订阅列表中。我想使用WordPress ajax来实现这一点。但它返回错误400错误请求。我的代码是:文件ajax新闻脚本。js公司: jQuery(document).ready(function($){ // Perform AJAX send news on form submit $(\'form#fnews\').on(\'submit\', funct