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.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格