【问题标题】:Ajax with GET in Wordpress在 Wordpress 中使用 GET 的 Ajax
【发布时间】:2016-07-05 14:31:10
【问题描述】:

下面的插件是一个简单的 ajax 请求插件:

/* /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' );
?>

浏览到http://mysite.co.uk/test/?fruit=Bannana 时控制台返回0?我期待它打印$_GET['fruit']的内容

【问题讨论】:

  • 尝试将函数和 add_action 部分放在 functions.php 中。它返回 0,因为这是一个无效的 ajax 操作,这意味着您的 add_action 不起作用。
  • 我使用脚本进行了这些更改,现在为相同的 URL 返回 (an empty string)
  • 那是因为你没有在 ajax 调用中发送任何东西。在你的 ajax 调用中,内部数据,发送 fruit : 'apple' 看看它是否有效。
  • 有了fruit: 'apple',我现在在控制台中看到了,谢谢。我真的很想拉出$_GET 参数并在我的函数中操作它们。
  • 送水果:'=isset($_GET['fruit']) ? $_GET['fruit'] : null?>' 而不是。

标签: php jquery ajax wordpress


【解决方案1】:

在你的 echo 语句之后使用 wp_die()。这是来自 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
}

更新您的代码我会将其更改为:

<?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();
 }
}

我还会在其他 if/then 结果中添加输出,以确保您将其添加到代码的正确部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2023-02-06
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多