【问题标题】:How do I get the correct php array format for WordPress Ajax $_POST data?如何为 WordPress Ajax $_POST 数据获取正确的 php 数组格式?
【发布时间】:2021-06-10 11:30:11
【问题描述】:

我第一次在 WordPress 中实现 ajax,但在这里遇到了一个障碍,我无法弄清楚问题所在。任何帮助表示赞赏。

所以我基本上是在尝试将数据传递给 WordPress 中的 ajax 回调。

JS:

    window.utils.http({
      method: 'POST',
      url: ajaxurl + '?action=ajax_submit',
      json: true,
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        test: 'testing123',
        quiz_results: {
          'a': 1,
          'b': 4,
          'c': 2
        }
      },
      onload: (response) => {
        console.log(response);
      },
    })

注意:即使使用 jQuery 的 ajax 函数,我也会遇到同样的问题

函数.php:

    function ajax_submit() {
        print_r($_POST);

        wp_die();
    }

    add_action('wp_ajax_ajax_submit', 'ajax_submit');
    add_action('wp_ajax_nopriv_ajax_submit', 'ajax_submit');

我的 JS 控制台日志响应:

Array
(
    [{"test":"testing123","quiz_results":{"a":0,"b":0,"c":0}}] => 
)

如您所见,php 数组的格式不正确,我也无法选择值。如果我 echo $_POST['test']echo $_POST[0]->['test'] 我什么都得不到。

谢谢

【问题讨论】:

  • 你能告诉我们这个print_r($_POST);的输出是什么

标签: javascript php ajax wordpress


【解决方案1】:

有时您无法通过超全局$_POST 访问数据。 在您的情况下,像这样修改您的 ajax_submit 函数

function ajax_submit() {
    // reading raw data from request body
    $data = file_get_contents("php://input");
    $data = json_decode($data, true);
    
    wp_send_json( $data, 200);
    wp_die();
}

更多信息见this回答

【讨论】:

    【解决方案2】:

    试试wp_send_json()

    function ajax_submit() {
        print_r($_POST);
        wp_send_json( $_POST );
        wp_die();
    }
    
    add_action('wp_ajax_ajax_submit', 'ajax_submit');
    add_action('wp_ajax_nopriv_ajax_submit', 'ajax_submit');
    

    【讨论】:

    • 谢谢,但不确定它在这里是否有效:{"{\"test\":\"testing123\",\"quiz_results\":{\"a\":0,\ "b\":0,\"c\":0}}":""} 我需要php端的数据,而不是JS端(主要是测试响应)
    • 你能告诉我们这个 print_r($_POST); 的输出是什么
    • 我很奇怪 echo $_POST['test'] 在这里不起作用,而网上到处都说应该。
    • print_r($_POST) 的输出是:数组([{"test":"testing123","quiz_results":{"a":0,"b":0,"c": 0}}] =>)
    • 尝试打印 echo ` "
      "; print_r($_POST); echo "
      ";` 并在您的问题中发布输出。
    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 2013-03-23
    • 2011-03-10
    • 2023-04-04
    • 2012-08-31
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多