Ajax with GET in Wordpress

落花浮王杯 提交于 2021-02-20 04:46:06

问题


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:


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.



来源:https://stackoverflow.com/questions/38206094/ajax-with-get-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!