Register jQuery - OOP WP

时间:2019-03-18 作者:Melinsuna

我发现this post 这似乎可以使Ajax脚本在OOP模型中工作。我发现通过类函数而不是其他文件添加脚本很有趣,这对我来说非常有用。但是,我无法将jQuery排入Wordpress的队列。我有一个错误:jQuery is not defined.

这是我的代码:

class fiche_content{
    private $file_base; 
    private $jenkins_url;

    function __construct($jenkins_token){
         $this->file_base = plugin_dir_path( dirname( __FILE__ ) ) . \'fiche.php\'; 
         $this->jenkins_url = $jenkins_url;

         $this->init(); 
    }

    function init() {
        add_action(\'wp_head\', array( $this, \'js_scripts\' ));
        add_action(\'wp_ajax_action_function\', array( $this, \'action_function\' ));
    }  

    function js_scripts(){
        $script = "
    <script type=\'text/javascript\'>     
        jQuery(document).ready(function($) {
            $(document).on(\'click\', \'#launchBuildForm\',function(e){
                var url =" . $this->jenkins_url . ";
                $.ajax({
                    method:\'post\',
                    url: url,
                    crossDomain: true,
                    dataType: \'jsonp\',
                    data: {
                        \'action\': \'action_function\'
                    },
                    success: function (msg) {
                        console.log(msg);
                        console.log(\'success\');
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        console.log(jqXHR, textStatus, errorThrown);
                    }
                });
            });
        }); 
    </script>
        ";
        echo $script;
    }


    function action_function(){
        echo \'test\';
        wp_die();
    }

1 个回复
SO网友:tmdesigned

您正在设置要在wp\\u head操作中添加的脚本。jQuery和大多数其他脚本都是作为wp\\u enqueue\\u scripts操作的一部分加载的。猜猜哪一个先到

Edit 事实并非如此。jQuery作为wp\\u default\\u脚本的一部分加载,该脚本发生在wp\\u头之前

我找到了这个list of the WordPress hook firing sequence 有帮助。它显示wp\\u head正好位于wp\\u enqueue\\u脚本之前。这意味着当脚本运行jQuery时,尚未加载jQuery。

只需更改init函数中的行:

add_action(\'wp_enqueue_scripts\', array( $this, \'js_scripts\' ));

我还建议将脚本放入外部文件中,然后将其排队。这样,您实际上可以指定依赖项(如jQuery)以及其他选项。。