首页 > 解决方案 > 管理菜单页面中的 Wordpress ajax 调用

问题描述

我正在尝试在我的自定义 wordpress 管理菜单页面中使用 ajax 调用的数据。

wp_localize_script工作正常:

wp_enqueue_script( 'ajax-function', plugin_dir_url( __FILE__ ) . 'JavaScript/ajax-function.js', array( 'jquery' ), $this->version,false );
wp_localize_script('ajax-function', 'WP_MY_AJAX',
     array(
       'security' => wp_create_nonce('wp-my-nonce'),
       'success' => 'this is a success',
       'error' => 'an error occurred'
     )
);

如果我单击该按钮,我的 ajax 会触发并且它的状态为 200。

jQuery(document).ready(function() {
    let message = jQuery('.table-message');
    jQuery('#ajax-test').on('click', function () {
        let data = 111;

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'get_edit_id',
                security: WP_MY_AJAX.security,
                edit_id: data
            },
            success: function ( response ) {
                //Do something
            },
            error: function ( error ) {
                jQuery('.error').remove();
                message.after('<div class="error"><p>' + WP_ESCORT_AJAX.error + '</p></div>');
            }
        });
    });

我最终得到了这个函数,它位于我的主插件文件中。

function my_escort_get_edit_id() {
    check_ajax_referer('wp-escort-nonce', 'security');

   echo $_POST['edit_id']
   die();
}
add_action('wp_ajax_get_edit_id', 'my_escort_get_edit_id');
add_action('wp_ajax_nopriv_get_edit_id', 'my_escort_get_edit_id');

但是我的目标是使用$_POST['edit_id']我的管理菜单页面功能:

function my_custom_admin_menu() {
    add_menu_page(
        __( 'My Menu', 'my-menu' ),
        __( 'My Menu', 'my-menu' ),
        'edit_posts',
        'my-menu-slug',
        'my_admin_page_function',
        'dashicons-universal-access',
        3 ) ;
}
add_action( 'admin_menu', 'my_custom_admin_menu' );

function my_admin_page_function() {
    require_once __DIR__ . '/View/Admin/Partials/cover-menu-models.php';
    requireModel('all');

    $controller = new ModelController();

    $modelQuery = $controller->modelQuery('all');
    echo $controller->renderModelDataTables($modelQuery, 'all');
    
    //I need the id here

}

我怎样才能做到这一点?

标签: javascriptphpjqueryajaxwordpress

解决方案


推荐阅读