1
jQuery(document).ready(function(e) {
jQuery('#m').click(function()
{
    //jQuery(this).fadeOut();
    var d='<?php echo $plugins;?>';
    jQuery.ajax({url:d,data:{q:10},type:GET,success: function(msg)
    {
        alert(msg);
    }
}
)
});

我必须开发自己的插件,基本上 Wordpress 有一个 admin-ajax 文件来处理这种类型的请求,那么我怎样才能使用它自己的文件来处理 Ajax 请求呢?

4

1 回答 1

1

为此,您需要这样做:

jQuery(document).ready(function($) {
    var data = {
        action: 'my_action',
        whatever: ajax_object.we_value      // We pass php values differently!
    };
    // We can also pass the url value separately from ajaxurl for front end AJAX implementations
    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

并在您的处理程序文件中:

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}

add_action('admin_enqueue_scripts', 'my_enqueue'); 函数 my_enqueue($hook) { if( 'index.php' != $hook ) return; // 仅适用于仪表板面板

wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));

// in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );

并且不要忘记将您的脚本加入队列:

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
    if( 'index.php' != $hook ) return;  // Only applies to dashboard panel

    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));

    // in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
    wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $email_nonce ) );
}
于 2013-06-04T05:45:53.520 回答