如何从管理仪表板中的插件发送AJAX请求?

时间:2018-01-02 作者:Uncle Vector

对于如何在wordpress插件中使用Ajax有点困惑。

您是否必须使用jQuery,因为目前我的代码是普通的javascript?

此外,我不确定我是否能够使用内联代码,还是必须将javascript放在单独的文件中才能使用wp\\U enque?

<?php
/*
 * Plugin Name:  React Test
 * Description:  Simple Reactjs test
 * Version:      0.0.1
 */


/**
 *  Add the plugin to the sub menu
 *  of the admin section
 */
function rt_addToAdminMenu(){
    $page_title = \'React Test\';
    $menu_title = \'React Test\';
    $capability = \'manage_options\';
    $menu_slug  = \'react-test\';
    $function   = \'rT_helloWorld\';
    $icon_url   = \'dashicons-media-code\';
    $position   = 4;

    add_menu_page( 
        $page_title,
        $menu_title,
        $capability,
        $menu_slug,
        $function,
        $icon_url,
        $position 
    );
 }
 add_action(\'admin_menu\', \'rt_addToAdminMenu\');


/*
 * This function is called 
 * from the admin menu in the wp dashboard
 */
 function rT_helloWorld(){
     //include the file with html and javascript to keep code cleaner
     //side note : javascript is written inline ie. <script>code here....</script> 
     require_once "test-file.php";
 }


/*
 * This function is called to 
 * handle the ajax request
 */
function rt_handleAjaxPost(){
   echo "Thanks";
   wp_die();
}
add_action( \'wp_ajax_rt_handleAjaxPost\', \'rt_handleAjaxPost\' );
下面是测试文件中的javascript。php,它发送ajax请求

<script>
//some more javascript above
...
buildButton.addEventListener("click", function(){        
    //send this via ajax to php so wordpress can use it in a post a or whereever

    var action  = "<?php echo admin_url(\'admin-ajax.php\'); ?>";
    var data    = {
         action  : "rt_handleAjaxPost",
         test    : "Hello"
    };
    var method  = "post";
    try {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readystate === 4 && xhr.status === 200){
                //do something here
                console.log("success");
                alert("success");
            }
        }
        xhr.open(method, action);
        xhr.send(data);
    } catch (e) {
        console.log(e.message);
    }
});
</script>
当代码运行时,我在javascript错误控制台中收到400个错误请求。

关于如何使此代码工作的任何帮助,如果可能,最好不要使用jquery。

提前感谢

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

下面是我在Wordpress中用于AJAX提交的基本片段。它确实使用jQuery,但没有理由香草不起作用。

你可以admin_enqueue_scripts() 这个<script>, 并在适当的页面上使用get_current_screen().

add_action( \'admin_menu\', function(){
    add_menu_page( \'My Plugin\', \'My Plugin\', \'manage_options\', \'my_plugin_slug\', \'my_plugin_page\', \'dashicons-cloud\' );
});

function my_plugin_page() {
    if (isset($_POST[\'my_plugin_ajax_submit\']))
        if ( wp_verify_nonce( $_POST[\'nonce\'], \'my_plugin_ajax_submit\' ) )
            my_plugin_ajax_submit();    
    ?>

    <button id=\'buildButton\'>Do Something</button>

    <script>
        jQuery(\'#buildButton\').click(function(){
            jQuery.ajax({
                type: \'post\',
                data: { 
                    "my_plugin_ajax_submit": "now",
                    "nonce" : "<?php echo wp_create_nonce( \'my_plugin_ajax_submit\' ); ?>"
                },
                success: function(response) { 
                    jQuery(\'#buildButton\').text("Somthing Done!");
                },
                error: function(response) { 
                    jQuery(\'#buildButton\').text("...error!");
                },
            });
        });
    </script>
    <?php
}

function my_plugin_ajax_submit() {

    // some php code that fires from AJAX click of #buildButton
    wp_mail( \'[email protected]\', \'my_plugin_ajax_submit() fired\', time());

    return true;
}

结束

相关推荐

在php请求之后不会调用操作

我想在用户填写完电子邮件表单后,通过mailchimp向用户发送一个下载链接。PHP请求侦听器正在调用my_function(), 但在这个函数中the action is not called.功能和操作正在运行。同样在放置do_action(); 内部createDownloadButton() 它将被称为。仅在将操作写入my_function() 这不管用?!内部functions.php: /** * Place a button *