【发布时间】:2018-05-09 09:00:39
【问题描述】:
在使用 jQuery 通过 Ajax 提交表单并对其进行序列化后,我无法使用 PHP 检索 post 变量。这是我的代码:
JS (main.js)
$.ajax({
url: WPaAjax.ajaxurl,
type: 'post',
data: {
action: 'send_message',
data: $(this).serialize()
},
success: function(response) {
$('.contact_form').html(response);
}
});
PHP (functions.php)
function load_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('main_js', get_stylesheet_directory_uri() . '/dist/scripts/main.js', array('jquery'), true);
wp_localize_script('main_js', 'WPaAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'load_scripts');
function send_message_function() {
echo $_POST['form_last_name'];
echo '<br><br>';
echo '<pre>' . print_r($_POST) . '</pre>';
exit;
}
add_action('wp_ajax_send_message', 'send_message_function');
add_action('wp_ajax_nopriv_send_message', 'send_message_function');
提交表单时,各个帖子变量(例如$_POST['form_last_name'])为空。
如果我打印_r $_POST 变量,我会得到这个:
Array ( [action] => send_message [data] => form_last_name=Johnson&form_first_name=David&form_email=djohnson%40hotmail.com&form_subject=&form_telephone=01110259923&form_code_postal=C11+3HR&form_message=test [some_variable] => some_value )
有什么建议吗?
【问题讨论】:
标签: jquery ajax wordpress post