我正在尝试为php创建钩子和函数来接收我的ajax调用,当响应发出警报时,我只收到0。
我想我的问题是,add\\u操作挂钩应该放在管理ajax的底部吗。php文件,还是应该转到其他地方?请记住,我的Ajax请求位于自定义模板上。php文件。
以下是参考代码:
add_action( \'wp_ajax_my_ajax_action\', \'my_ajax_action_callback\' );
add_action( \'wp_ajax_nopriv_my_ajax_action\', \'my_ajax_action_callback\' );
function my_ajax_action_callback(){
echo "Baffles";
$first_name = isset( $_POST[\'first_name\'] ) ? $_POST[\'first_name\'] : \'N/A\';
$last_name = isset( $_POST[\'last_name\'] ) ? $_POST[\'last_name\'] : \'N/A\';
?>
<p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p>
<?php
die(); // required. to end AJAX request.
}
Jquery/Ajax请求
jQuery(document).ready(function () {
$.ajax({
type: \'POST\',
url: \'../wp-admin/admin-ajax.php\',
data: {
action : \'my_ajax_action\', // load function hooked to: "wp_ajax_*" action hook
first_name : \'John\', // PHP: $_POST[\'first_name\']
last_name : \'Cena\', // PHP: $_POST[\'last_name\']
}, success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
最合适的回答,由SO网友:DHL17 整理而成
可能是这里的错误
add_action( \'wp_ajax_my_ajax_action\', \'my_ajax_action_callback\' );
add_action( \'wp_ajax_nopriv_my_ajax_action\', \'my_ajax_action_callback\' );
更改为
add_action( \'wp_ajax_my_ajax_action_callback\', \'my_ajax_action_callback\' );
add_action(\'wp_ajax_nopriv_my_ajax_action_callback\',\'my_ajax_action_callback\' );
在ajax更改中:
action : \'my_ajax_action_callback
转到
functions.php
并添加:
require(dirname(__FILE__) . \'/custom_template.php\');
确保您的ajax
url
是正确的!!
SO网友:Seth Spivey
这是对我有用的东西。我仍在试图找出如何将php结果输出到数组中,以便将其存储在select元素中。当我弄明白后,我会更新这个。
function add_ajaxurl_cdata_to_front(){ ?>
<script type="text/javascript">
ajaxurl = \'<?php echo admin_url( \'admin-ajax.php\'); ?>\'
</script>
<?php }
add_action( \'wp_head\', \'add_ajaxurl_cdata_to_front\', 1);
add_action( \'wp_footer\', \'add_js_to_wp_footer\' );
function add_js_to_wp_footer() { ?>
<script type="text/javascript">
jQuery("#field_6_17 select").on(\'change\', function() {
var product_line = jQuery(this).val();
jQuery.ajax({
type: \'POST\',
url: ajaxurl,
data: {
"action": "view_site_description",
first_name : \'John\', // PHP: $_POST[\'first_name\']
last_name : \'Cena\',
}, success: function(data){
console.log(\'product_line\');
jQuery(\'select#input_6_26 option\').html(data);
}
});
return false;
});
</script>
<?php }
function view_site_description(){
global $wpdb;
$first_name = isset( $_POST[\'first_name\'] ) ? $_POST[\'first_name\'] : \'N/A\';
$last_name = isset( $_POST[\'last_name\'] ) ? $_POST[\'last_name\'] : \'N/A\';
?>
<p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p><?php
die();
}
add_action( \'wp_ajax_view_site_description\', \'view_site_description\' );
add_action( \'wp_ajax_nopriv_view_site_description\', \'view_site_description\' );