我在函数中使用了以下代码。php页面
add_action(\'woocommerce_product_thumbnails\', \'my_ajax_button\');
function my_ajax_button() {
echo \'<button class="buy-this-room myajax" id="buy_this_room" >Buy This Room</button>
<button class="buy-this-design myajax" id="buy_this_design" >Buy This Design</button>\';
}
add_action(\'wp_head\', \'my_action_javascript\');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var ajaxurl = "<?php admin_url(\'admin-ajax.php\'); ?>";
$(\'.myajax\').click(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
}
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 = $_POST[\'whatever\'];
$whatever += 10;
echo $whatever;
exit(); // this is required to return a proper result & exit is faster than
}
Ajax调用正在进行,但我没有得到结果。警报显示如下
Got this from the server: <!DOCTYPE html>
<!--[if IE 7 ]><html class="ie ie7" lang="en-US"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en-US"> <![endif]-->
<!--[if IE 9 ]><html class="ie ie9" lang="en-US"> <![endif]-->
<html lang="en-US">
<head>
有人能帮忙吗!
谢谢
最合适的回答,由SO网友:WPTC-Troop 整理而成
看起来您没有打印管理ajax URL。
add_action(\'wp_head\', \'my_action_javascript\');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var ajaxurl = "<?php echo admin_url(\'admin-ajax.php\'); ?>";
$(\'.myajax\').click(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
}
请查看我正在使用echo打印管理员url。由于ajax调用中没有URL,因此您将获得整个页面。
其他信息:对于未登录的用户,请使用wp_ajax_nopriv