无法使用jQuery序列化的PHP post变量检索

时间:2018-05-09 09:00:40

标签: jquery ajax wordpress post

使用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'])为空。

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

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

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

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数据。

答案 1 :(得分:0)

这就是我要解决的问题:

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']