【问题标题】:Can't retrieve with PHP post variables serialized with jQuery无法使用 jQuery 序列化的 PHP post 变量检索
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢它确实有效,但它是做这整件事的正确方法吗?对我来说这似乎有点 hacky,你觉得呢?
    • 在您看来,什么是 hacky?我只是向您展示如何解码上面有查询字符串的 post 字段,正如我看到的 $_POST['form_last_name']
    【解决方案2】:

    这就是我的解决方法:

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

    【讨论】:

    • 谢谢,但是使用你的代码我得到一个“400(错误请求)”错误
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2013-04-27
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    相关资源
    最近更新 更多