dongwu3747 2015-03-09 21:29
浏览 64
已采纳

调用AJAX时,Wordpress插件中的未定义索引

I created plugin for Wordpress and am now trying to learn Ajax in plugin.

When I call my function:

wp-admin/admin-ajax.php?action=my_action

I get this error:

Notice: Undefined index: whatever

This is my function

add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        var data = {
            'action': 'my_action',
            'whatever': 1234
        };
        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        $.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
    </script> <?php
}

and function call back

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
}

What's causing this error and how can I fix it?

  • 写回答

1条回答 默认 最新

  • 普通网友 2015-03-09 21:39
    关注

    When you make a request to wp-admin/admin-ajax.php?action=my_action it only includes the action query string parameter and not the whatever parameter that the callback function in WordPress is expecting.

    If you want this to work in a browser test from the address bar replace $_POST['whatever'] with $_REQUEST['whatever'] and use this in your browser wp-admin/admin-ajax.php?action=my_action&whatever=1234 - this will pass whatever as a GET whereas in your ajax it is a POST, but $_REQUEST will see both.

    That said, your example code is correct - I even tested it on a local install. When your JavaScript executes it will include both parameters as part of the data object, which can then be process in the ajax handler. Just load your site in a browser and the code should alert unless you have other JavaScript errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵