【问题标题】:Sending data alongside FormData as one Object in AJAX在 AJAX 中将数据与 FormData 一起作为一个对象发送
【发布时间】:2019-12-16 16:56:15
【问题描述】:

我正在尝试将 JSON 数组中的 FormData 传递给 AJAX 脚本:

$('#form').submit(function(e)
{
    e.preventDefault();

    let formData = new FormData(this),
        data = {'action': 'insert', 'data': formData};

    $.ajax({
        data: data,
        url: '/wp-content/plugins/eng-dealer-map/bin/Admin.php',
        type: 'post',
        cache: false,
        contentType: false,
        processData: false,
        success: function(res) {console.log(res)},
        error: function(res) {console.log(res)}
    })
});

然后是/bin/Admin.php

<?php
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);

    $ds = DIRECTORY_SEPARATOR;

    require_once $_SERVER['DOCUMENT_ROOT']. $ds. 'wp-content'. $ds. 'plugins'. $ds. 'eng-dealer-map'. $ds. 'vendor'. $ds. 'autoload.php';

    var_dump($_POST);
    $admin = new \App\Endpoint\Admin(['action' => $_POST['action'], 'data' => $_POST['data']]);
    echo $admin->execute();

这又最终进入了这个(缩小的)类:

<?php
    namespace App\Endpoint;

    class Admin
    {
        protected $db;
        protected $table;

        protected $sql;
        protected $data;

        public function __construct($foo)
        {
            require_once $_SERVER['DOCUMENT_ROOT']. DIRECTORY_SEPARATOR. 'wp-config.php';
            global $wpdb;

            $this->db = $wpdb;
            $this->table = '`'. $this->db->prefix .'trey_is_the_best`';

            $this->sql = $this->build($foo['action']);
            $this->data = $foo['data'];
        }

        public function build(string $action)
        {
            switch($action)
            {
                case 'insert': return $this->insertSql(); break;
                case 'update': return $this->updateSql(); break;
                case 'remove': return $this->removeSql(); break;
                default: throw new \Exception('trey'); break;
            }
        }

        public function execute()
        {
            if (!empty($this->sql)) {
                try {
                    if ($this->db->query($this->db->prepare($this->sql, $this->data))) {
                        return true;
                    } else {
                        throw new \Exception($this->db->last_error);
                    }
                } catch (\Exception $e) {
                    throw new \Exception($e->getMessage());
                }
            } else {
                return 'SQL empty!';
            }
        }
    }

不幸的是,$_POST 似乎在途中迷路了。在我的 JS 中添加这个:

for (let pair of formData.entries())
{
    console.log(pair[0]+ ', ' + pair[1]);
}

正确显示我的数据。然后我 var_dump($_POST)bin/Admin.php 中显示一个空数组。

我将'data': formData 更改为'data': 'hello, world',所以我觉得FormData 不喜欢在包含其他元素的JSON 数组中?

那么如何将带有其他元素的 FormData 发送到我的 AJAX 脚本?我知道我可以使用:

formData.append('action', 'action-value')

但是当它可以作为一个对象发送到我的脚本时,感觉就像是一个额外的步骤。

我也尝试在formData 上使用JSON.stringify,但同样没有。有没有一种方法可以在不使用.append() 的情况下将formData 其他数据作为一个对象发送?还是这是我唯一的选择?

【问题讨论】:

  • file_get_contents('php://input') 中有什么内容?
  • @FelippeDuarte 啊有趣.. [object Object]
  • 像这样编写data 是个坏主意,但如果你使用let data = {'action': 'insert', 'data': $(this).serialize()};,你可以让它工作。我会将action 附加到表单数据中。
  • @FelippeDuarte 啊,有趣的阅读!所以使用php://input 我可以得到[object Object] - 那么我该如何解析呢?我有一种感觉,formData 不喜欢成为对象的一部分,感觉它希望一切都成为它的一部分,而不是共存

标签: javascript php ajax


【解决方案1】:

我有一种感觉 FormData 不喜欢在一个带有其他元素的 JSON 数组中?

正确。您不能将 FormData 转换为 JSON。

那么如何将带有其他元素的 FormData 发送到我的 AJAX 脚本?

将额外的数据添加到 FormData。

我知道我可以使用:

formData.append('action', 'action-value')

是的,这样做。

但是当它可以作为一个对象发送到我的脚本时,感觉就像是一个额外的步骤。

FormData 对象一个对象。您只需将数据添加到其中,而不是将数据添加到不同的对象,然后尝试将来自FormData 的数据添加到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    相关资源
    最近更新 更多