jquery FormData和Zend Framework 2

问题描述 投票:0回答:1

我正在尝试通过FormData(使用jQuery)将数据发送到我的控制器,但是我遇到了数据为空的问题。我也不确定为什么,当我使用console.log()时,文本显示在控制台中但是当我用ajax传递它时,我收到错误,我设置说“状态文本不能为空”。我是使用FormData的新手,所以如果我不清楚我说的话,我很抱歉。

这是我的代码:

jQuery -

$('#post-status').on('click', function() {
    if ($('#status').html() != "Status: " && $('#status').html() != "") {
        var status = $('#status').html();

        var getstatus;
        var getfile;

        var formData = new FormData();

        if (document.getElementById('status-photo') == null) {
            formData.append("statustext", status);

            getstatus = formData.get("statustext");
        } else {
            formData.append("statustext", status);
            formData.append("userfile", document.getElementById('status-photo').files[0]);

            var getstatus = formData.get("statustext");
            var getfile = formData.get("userfile");
                                    }

            //console.log(getstatus);
            //return false;

            $('#status-msg').html("");

            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: "/members/status/post-status",
                dataType: "json",
                data: formData
            }).done(function(msg) {
                $('#status-msg').html(msg.success);

                console.log(msg);

                $('#status').html('Status: ');

                $('#added-status-photos').attr('style', 'display: none;');
                $('#delete-include-pic').attr('style', 'display: none;');

                $('#include-pic').attr('style', 'display: block;');

                // update status text
                $.getJSON('/members/status/get-status', function(stat) {
                    $('#current-status').html("Current Status: " + stat.status);
                });
            }).fail(function(msg) {
                console.log(msg);
                $('#status-msg').html(msg.fail);

                $('#added-status-photos').attr('style', 'display: none;');
                $('#delete-include-pic').attr('style', 'display: none;');

                $('#include-pic').attr('style', 'display: block;');
            }); 
        } else {
            $('#status-msg').html("Please enter a valid status.");
            return;
        }
});

控制器 -

public function poststatusAction()
{
    $layout = $this->layout();
    $layout->setTerminal(true);

    $view_model = new ViewModel();
    $view_model->setTerminal(true);

    if ($this->request->isPost()) {
        try {
            $status = $this->params()->fromPost('status');
            $file = $this->params()->fromPost('file');

            if (!empty($file)) {
                if ($this->getStatusService()->postStatus($status, array('tmp_name' => $_FILES[$file]['tmp_name'], 
                    'name' => $_FILES[$file]['name']))) {
                    echo json_encode(array('success' => 'Status updated'));
                } 
            } else {
                if ($this->getStatusService()->postStatus($status)) {
                    echo json_encode(array('success' => 'Status updated'));
                }
            }
        } catch (StatusException $e) {
            echo json_encode(array('fail' => $e->getMessage()));
        }
    }

    return $view_model;
}

最后的模型 -

public function postStatus($status, array $image = array())
{
    if (empty($status)) {
        throw new StatusException("Status text cannot be left empty.");
    } else {
        // get the user's id based on $this->user
        $this->select->columns(array('id'))
        ->where(array('username' => $this->user));

        $query = $this->sql->getAdapter()->query(
            $this->sql->buildSqlString($this->select),
            Adapter::QUERY_MODE_EXECUTE
        );

        if ($query->count() > 0) {
            foreach ($query as $result) {
                $row = $result;
            }

            $select = $this->gateway->select(array('id' => $row['id']));

            if ($select->count() > 0) {
                // update status
                $update_data = array(
                    'status' => $status,
                );

                $update = $this->gateway->update($update_data, array('id' => $row['id']));

                if ($update > 0) {
                    return true;
                } else {
                    throw new StatusException("Error posting status.");
                }
            } else {
                // insert status
                $insert_data = array(
                    'id'     => $row['id'],
                    'status' => $row['status'],
                );

                $insert = $this->gateway->insert($insert_data);

                if ($insert > 0) {
                    // put image into status folder (if not null)
                    if (count($image) > 0) {
                        if (!@is_dir(getcwd() . '/public/images/profile/' . $this->user . '/status')) {
                            // make the status directory
                            // then insert any images if found
                            mkdir(getcwd() . '/public/images/profile/' . $this->user . '/status');

                            if (@is_uploaded_file($image['name'])) {
                                move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
                                return true;
                            } else {
                                throw new StatusException("Error uploading your image for your status.");
                            }
                        } else {
                            // insert any images if found
                            if (@is_uploaded_file($image['name'])) {
                                move_uploaded_file($image['tmp_name'], getcwd() . '/public/images/profile/' . $this->user . '/status/' . $image['name']);
                                return true;
                            } else {
                                throw new StatusException("Error uploading your image for your status.");
                            }
                        }
                    } 

                    // no image
                    return true;
                } else {
                    throw new StatusException("Error posting status.");
                }
            }
        } else {
            throw new StatusException("Invalid username passed.");
        }
    }
}

我收到的错误信息是在模型的第一行

throw new StatusException("Status text cannot be left empty.");

我已经包含了两个截图,希望可能有所帮助,如果我再也不清楚

enter image description here enter image description here

任何帮助,将不胜感激。

谢谢!

jquery zend-framework2 form-data
1个回答
1
投票

尝试更改您的ajax代码,如下所示。

$.ajax({
            type: "POST",
            contentType: false,
            processData: false,
            url: "/members/status/post-status",
            dataType: "json",
            data: formData
        }).

你的zend控制器和动作代码似乎很好。

© www.soinside.com 2019 - 2024. All rights reserved.