jQuery ajax成功方法无法正常工作

时间:2017-08-05 20:16:18

标签: php jquery ajax wordpress elementor

我为Elementor插件开发了一个名为 carousel slider 的自定义小部件。我为多个选择设置了元素或默认设置字段select2。我在select2字段中填充Elementor Libray模板。通常工作正常。但我想添加从编辑器预览iframe创建的新创建的模板。这里的模板是使用ajax方法创建的,该方法不加载页面。

要添加新创建的项目,我使用了Elementor JS hook elementor.hooks.addAction( 'panel/open_editor/widget/widget-type,当要编辑任何窗口小部件或打开该窗口小部件类型的编辑器时,它会被触发。使用jQuery ajax我设法将新创建的模板添加到select2字段。但问题是"当我第一次在预览iframe中点击该窗口小部件类型(在我的案例轮播滑块中)并打开编辑器时,新创建的模板已添加并显示在select2选项中值。现在我关闭那个编辑器,再一次打开我的小部件的编辑器,点击轮播小部件,新添加的模板消失了。我无法弄清楚问题。我的代码在下面..

(function( $ ) {
    $(document).ready( function() {
        elementor.hooks.addAction( 'panel/open_editor/widget/premium-carousel-widget', function( panel, model, view ) {
            $.ajax({
                url : template_update.ajax_url,
                type : 'POST',
                data : {
                    action : 'update_template',
                    whatever : 'yes'
                },
                success : function( data ) {
                    if( data !== '' ) {
                        console.log( data );
                        $('select[data-setting=premium_carousel_slider_content]').append( $(data ) );
                    }
                    console.log( 'hello' );
                }
            });
        });
    });
})(jQuery);

PHP代码如下。我使用了WordPress ajax API。

public function updating_template_after_save() {
    if( $_POST['whatever'] ) {
        $pagelist = get_posts(array(
            'post_type' => 'elementor_library',
            'showposts' => 999,
        ));

        $options = array();
        if ( ! empty( $pagelist ) && ! is_wp_error( $pagelist ) ){
            foreach ( $pagelist as $post ) {
                $options[ $post->ID ] = __( $post->post_title, 'premium_elemnetor' );
            } 
        }

        $old_items = get_option( 'temp_count' );
        if( $old_items != $options ) {
            $html = '';
            $new_item = array_diff( $options, $old_items );
            foreach( $new_item as $key => $value ) {
                $html .= '<option value="'.$key.'">'. $value .'</option>';
            }
            echo $html;
            update_option( 'temp_count', $options );
        }
    }
    die();
}

0 个答案:

没有答案