weixin_33676492 2016-07-05 14:31 采纳率: 0%
浏览 49

在Wordpress中使用GET进行Ajax

The plugin below is a bare-bones ajax request plugin:

/* /wp-content/plugins/ajax-test/ajax-test.php */
/**
 * Plugin Name: Ajax Test
 * Plugin URI: http://mysite.co.uk
 * Description: This is a plugin that allows us to test Ajax functionality in WordPress
 * Version: 1.0.0
 * Author: Me
 * Author URI: http://mysite.co.uk
 * License: GPL2
 */
add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
 wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true );
    wp_localize_script( 'test', 'MYajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}



# /wp-content/plugins/ajax-test/test.js
jQuery(document).ready( function($) {
 $.ajax({
    url: MYajax.ajax_url,
    type : 'get',
    data : {
        action : 'example_ajax_request'
    },
    success: function( response ) {
        console.log(response);
    }
 })
})

<?php /* page-test.php */
 get_header(); ?>

<?php 
function example_ajax_request() {
 if ( isset($_GET) ) {
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
        $fruit = $_GET['fruit'];
        echo $fruit;
    }
    die();
 }
}

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
?>

Upons browsing to http://mysite.co.uk/test/?fruit=Bannana the console returns 0? I'm expecting it to print the contents of $_GET['fruit']

  • 写回答

1条回答 默认 最新

  • weixin_33725239 2016-07-05 16:39
    关注

    Use wp_die() after your echo statement. Here is the sample code from the Codex.

    <?php 
    
    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;
    
        wp_die(); // this is required to terminate immediately and return a proper response
    }
    

    Updating your code I would change it to:

    <?php 
    function example_ajax_request() {
     if ( isset($_GET) ) {
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
            $fruit = $_GET['fruit'];
            echo $fruit;
            wp_die(); //Added to get proper output.
        }
        die();
     }
    }
    

    I would also add outputs at other if/then outcomes to make sure you are making it to the proper part of your code.

    评论

报告相同问题?