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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献