无法使用使用 jQuery 序列化的 PHP 后变量进行检索



使用 jQuery 通过 Ajax 提交表单并对其进行序列化时,我无法使用 PHP 检索帖子变量。这是我的代码:

JS(主.js(

$.ajax({
url: WPaAjax.ajaxurl,
type: 'post',      
data: {
action: 'send_message',
data: $(this).serialize()
},
success: function(response) {
$('.contact_form').html(response);
}
});

PHP(函数.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'](为空。

如果我print_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 )

有什么建议吗?

为了从您粘贴的结构中检索值:

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 
)

按如下方式操作:

parse_str($_POST['data'], $temp)
// Now you can access those vars on $temp
echo $temp['form_last_name'];
echo $temp['form_first_name'];

看到您正在尝试访问一个字段$_POST['form_last_name']该字段实际上位于帖子$_POST['data']字段的查询字符串内。

查看 php 方法parse_str并仔细查看您收到的$_POST数据。

这就是我解决它的方法:

var data = { action: 'send_message' },
$form = $(this);
$.each( $form.serializeArray(), function () {
data[ this.name ] = this.value;
} );
$.ajax( {
...
data: JSON.stringify(data),
...
} )

然后你可以通过 php 访问变量作为$_POST['action']$_POST['form_last_name']

最新更新