AJAX Wordpress网址

时间:2014-06-12 06:39:44

标签: jquery ajax wordpress

我遇到了AJAX的问题。

jQuery.ajax({
    type:"POST",
    url: "/wp-admin/admin-ajax.php", // our PHP handler file
    data: "myDataString",
    success:function(results){
        alert(results);
    }
)};

未经授权,此请求不起作用。如何在WP中添加自定义URL到操作?

2 个答案:

答案 0 :(得分:1)

问题不是很明确,但我会帮助您为已登录和未登录的用户添加AJAX操作。

// Add this to functions.php
// Let's enqueue our javascript file
function include_ajax_js() {

    wp_register_script(
        'ajax-custom-script',
        get_stylesheet_directory_uri() . '/js/ajax.js',
        array( 'jquery' )
    );

   // Add data your script that you can normally
   // only get from the server side of WordPress.

   $localize = array(
       'ajaxurl' => admin_url('admin-ajax.php'),
       // Securing your WordPress plugin AJAX calls using nonces
       'auth' => wp_create_nonce('_check__ajax_100')
   );
   wp_localize_script('ajax-custom-script', 'custom_ajax_vars', $localize);

   wp_enqueue_script('ajax-custom-script');

}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

// Let's make function to handle AJAX requests
function my_ajax_action() {

    // Check nonce
    check_ajax_referer( '_check__ajax_100', 'nonce_field' );

    // Let's display some useful information
    // May be you need to check if the user is still logged in

    $user_greeting = is_user_logged_in() ? 'Hello User !' : 'Hello Guest !';
    $data = array( 'msg' => $user_status );

    echo json_encode($data); // encode the output to JSON
    die();
}
add_action( 'wp_ajax_check_status', 'my_ajax_action' );
// wp_ajax_nopriv_ executes for users that are not logged in
add_action( 'wp_ajax_nopriv_check_status', 'my_ajax_action' );

现在有足够的PHP,让我们创建一个ajax.js

jQuery(document).ready(function(){

    jQuery.ajax({
        type:"POST",
        // We can easily get the AJAX Url from the object we've created before
        url: custom_ajax_vars.ajaxurl,
        // Data should be sent as an object
        data: { action: check_status, nonce_field: custom_ajax_vars.nonce },
        success:function(data){
            alert(data.status);
        }
    )}
})
})

答案 1 :(得分:0)

试试这个:

var username = "user123";
var password = "pass123";

//var username = "";
//var password = "";    
var headers = {}; //list of headers

if(username && password) //user and pass exists
    headers['Authorization'] = "Basic " + btoa(username + ":" + password);

     jQuery.ajax({

     type:"POST",

    url: http://siteurl.com/wp-admin/admin-ajax.php,

  data: "myDataString",
    headers: headers, //use our headers 
     success:function(results){

      alert(results);

    }

    )};