使用 Ajax 将表单数据发布到 ZF2 控制器

编辑-
我已经在下面发布了答案.

问题是我不明白按下提交按钮时 ZF2 如何/在哪里发布表单数据.所以,当我做
if ($this->getRequest()->isPost()){
在下面的 ajax 调用之后,它告诉我没有发布任何数据.

当我执行上述 isPost() if 语句时,它在我点击提交按钮时完美运行,告诉我数据已发布,随后告诉我表单数据有效.

The question is that I don't understand how/where ZF2 posts form data when a submit button is pressed. So, when I do
if ($this->getRequest()->isPost()){
after the ajax call below, it tells me that no data has been posted.

When I do the above isPost() if statement it works perfectly when I hit the submit button, telling me the data has been posted and subsequently telling me that the form data is valid.

这里是ajax调用-

            <script>
                $.ajax({
                    url: urlform,
                    type: 'POST',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    async: true,
                    data: ($("#newThoughtForm").serialize() + '&submit=go'),
                    success: function () {
                        console.log('SUBMIT WORKS');
                        setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
                        }, 1000);
                    },
//This keeps getting executed because there is no response, as the controller action is not run on a Post()
                    error: function () {
                        console.log('There is error while submit');
                        setTimeout(function () { <?php echo $this->invokeIndexAction()->test(); ?> ;
                        }, 1000);
                    }
//I assume the data won't get pushed to the server if there is no response,
//but I can't figure out how to give a response in ZF2 since the controller is not
//run when the Post() is made. 
                });

这是表格-

            use ZendFormForm;

            class newAlbumForm extends Form
            {
                public function __construct()
                {
                    parent::__construct('newAlbumForm');
                    $this->setAttribute('method', 'post');

                    $this->add(array(
                        'type' => 'AlbumModuleForm
ewAlbumFieldset',
                        'options' => array(
                            'use_as_base_fieldset' => true
                        )
                    ));

                    $this->add(array(
                            'name' => 'submit',
                                'attributes' => array(
                                    'type' => 'submit',
                                    'value' => 'go'
                        ),
                    ));
                }
            }



ajax调用请求-



The request for the ajax call-

            Request URL:http://test/newAlbum.html
            Request Method:POST
            Status Code:200 OK
            Request Headersview source
            Accept:*/*
            Accept-Encoding:gzip,deflate,sdch
            Accept-Language:en-US,en;q=0.8
            Connection:keep-alive
            Content-Length:46
            Content-Type:application/x-www-form-urlencoded; charset=UTF-8
            Cookie:PHPSESSID=h46r1fmj35d1vu11nua3r49he4
            Host:test
            Origin:http://test
            Referer:http://test/newAlbum.html
            User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
            X-Requested-With:XMLHttpRequest
            Form Dataview sourceview URL encoded
            album[albumText]:hello world
            submit:go
            Response Headersview source
            Connection:Keep-Alive
            Content-Length:4139
            Content-Type:text/html
            Date:Sun, 20 Oct 2013 16:52:15 GMT
            Keep-Alive:timeout=5, max=99
            Server:Apache/2.4.4 (Win64) PHP/5.4.12
            X-Powered-By:PHP/5.4.12

提交按钮的请求-

            Request URL:http://test/newAlbum.html
            Request Method:POST
            Status Code:200 OK
            Request Headersview source
            Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
            Accept-Encoding:gzip,deflate,sdch
            Accept-Language:en-US,en;q=0.8
            Connection:keep-alive
            Content-Length:46
            Content-Type:application/x-www-form-urlencoded
            Cookie:PHPSESSID=h46r1fmj35d1vu11nua3r49he4
            Host:test
            Origin:http://test
            Referer:http://test/newAlbum.html
            User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
            Form Dataview sourceview URL encoded
            album[albumText]:hello world
            submit:go
            Response Headersview source
            Connection:Keep-Alive
            Content-Length:4139
            Content-Type:text/html
            Date:Sun, 20 Oct 2013 16:52:14 GMT
            Keep-Alive:timeout=5, max=100
            Server:Apache/2.4.4 (Win64) PHP/5.4.12
            X-Powered-By:PHP/5.4.12



这是控制器上的 indexAction() 以确保完整性-



Here is the indexAction() on the controller for completeness-

            public function indexAction()
            {
                echo 'console.log("Index Action is Called");';

                $form = new AlbumModuleForm
ewAlbumForm();
                if ($this->getRequest()->isPost()){
                    echo 'console.log("Data posted");';

                    $form->setData($this->getRequest()->getPost());
                    if ($form->isValid()){
                        echo 'console.log("Form Valid");';

                        //todo
                        $this->forward()->dispatch('newAlbum', array('action' => 'submitAlbum'));
                        return new ViewModel(
                            array(
                                    'form' => $form
                            )
                        );
                    } else {
                        echo 'console.log("Form Invalid");';

                        return new ViewModel(
                            array(
                                    'form' => $form
                            )
                        );
                    }
                } else {
                    echo 'console.log("No data posted")';
                    return new ViewModel(
                            array(
                                    'form' => $form
                            )
                        );
                }
            }

正如我在开头所说的,isPost() 类在按钮提交表单时会返回 true 值,但是当通过 Ajax 提交表单时它会返回 false 值.

As I stated at the beginning, the isPost() class will return a value of true when the button submits the form, but it will return a value of false when the form is submitted through Ajax.

编辑-
我已经在下面发布了答案.

推荐答案

通常当你从 ajax 发送数据时,你不需要再次渲染你的模板,这就是 ViewModel 所做的.

Usually when you send data from ajax, you don't need to render your template again, and that's what ViewModel do.

尝试将 json 策略添加到您的 module.config.php

Try to add json strategy to your module.config.php

'view_manager' => array(
    //other configuration
    'strategies' => array(
        'ViewJsonStrategy',
    ),
),

那么您的操作应该如下所示:

Then your action should look like this:

public function ajaxAction()
{
    $request = $this->getRequest();

    if ($request->isXmlHttpRequest()){ // If it's ajax call
        $data = $request->getPost('data'));
        ...
    }


    return new JsonModel($formData);
}

相关文章