[英]Undefined index in Wordpress plugin when call AJAX
I created plugin for Wordpress and am now trying to learn Ajax in plugin . 我为Wordpress创建了插件,现在尝试在plugin中学习Ajax 。
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? 是什么导致此错误,我该如何解决?
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. 当您向
wp-admin/admin-ajax.php?action=my_action
发出请求时,它仅包含action
查询字符串参数,而不包括WordPress中的回调函数期望的whatever
参数。
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. 如果您希望它在地址栏中的浏览器测试中起作用,请将
$_POST['whatever']
替换$_POST['whatever']
$_REQUEST['whatever']
,然后在浏览器中使用它wp-admin/admin-ajax.php?action=my_action&whatever=1234
-这将通过whatever
一个GET
,而在你的Ajax这是一个POST
,但$_REQUEST
会看到两者。
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. 当您的JavaScript执行时,这两个参数都将作为
data
对象的一部分包含在内,然后可以在ajax处理程序中进行处理。 Just load your site in a browser and the code should alert unless you have other JavaScript errors. 只要将您的网站加载到浏览器中,代码就会发出警报,除非您遇到其他JavaScript错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.