SilverStripe通过Ajax提交HTML表单

时间:2016-03-09 15:13:00

标签: javascript php jquery ajax silverstripe

我想通过Ajax将数据从简单的HTML表单传递给控制器​​,然后处理数据并返回响应。

目前我有以下内容:

HomePage.ss

$('form.submit-form').submit(function() {
    $.ajax({
        type: 'POST',
        url: 'processForm',
        data: $(this).serialize(),
        success: function(data) {
            alert('data received');
        }
    });
});

的JavaScript

class HomePage_Controller extends Page_Controller {
    public function events() {
        $events = CalendarEvent::get();
        return $events;
    }

    public function processForm() {
        if (Director::is_ajax()) {
            echo 'ajax received';
        } else {
            //return $this->httpError(404);
            return 'not ajax';
        }
    }
}

HomePage.php

application/libraries

在开发人员工具中,我可以看到我得到了xhr processForm,其中找不到404错误。

如何使用SilverStripe控制器正确使用此Ajax表单?

2 个答案:

答案 0 :(得分:3)

蜘蛛,

我做过类似下面的事情。这是一个快速而肮脏的演示,尚未经过测试,但它可能会让您走上正确的道路。如果您不熟悉SilverStripe中表单的工作方式,那么SilverStripe中的前端表单会有一课。我发现这些课程对个人有用,并为课程提供了代码:http://www.silverstripe.org/learn/lessons/introduction-to-frontend-forms?ref=hub

<强> page.php文件

<?php

class Page extends SiteTree
{



}

class Page_Controller extends Content_Controller
{

    private static $allowed_actions = array(
        'MyForm',
    );

    public function MyForm()
    {
        Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.min.js');
        Requirements::javascript(THIRDPARTY_DIR . '/jquery-validate/jquery.validate.min.js');
        Requirements::javascript('/path/to/your/validation/script.js');

        $fields = FieldList::create(
            TextField::create('name')
                ->setTitle('Name')
        );

        $actions = FieldList::create(
            FormAction::create('doSubmit')
                ->setTitle('Submit')
        );

        $requiredFields = RequiredFields::create(
            'name'
        );

        $form = Form::create($this, 'MyForm', $fields, $actions, $requiredFields);

        return $form;
    }

    public function doSubmit($data, $form)
    {
        //process $data or create your new object and simpley $form->saveInto($yourObject); then $yourObject->write()
        //then deal with ajax stuff
        if ($this->request->isAjax()) {
            return $this->customise(array(
                'YourTemplateVar' => 'Your Value'
            ))->renderWith('YourIncludeFile');
        } else {
            //this would be if it wasn't an ajax request, generally a redirect to success/failure page
        }
    }

}

<强> YourValidationScript.js

(function ($) {
    $(function () {
        $('#MyForm_Form').validate({
            submitHandler: function (form) {
                $.ajax({
                        type: $(form).attr('method'),
                        url: $(form).attr('action') + "?isAjax=1",
                        data: $(form).serialize()
                    })
                    .done(function (response) {
                        $('.content').html(response);
                    })
                    .fail(function (xhr) {
                        alert('Error: ' + xhr.responseText);
                    });
            },
            rules: {
                name: "required"
            }
        });
    })
})(jQuery);

答案 1 :(得分:2)

您需要了解如何在SilverStripe中处理HTTP请求路由。

当您发送请求POST / processForm时,它被视为页面并由ModelAsController管理。这就是为什么你得到404错误 - 没有使用URLSegment = processForm的SiteTree记录。

解决方案1 ​​

使用表单对象。它在运行时自动创建所有路由配置。阅读更多 https://docs.silverstripe.org/en/3.3/tutorials/forms/ https://docs.silverstripe.org/en/3.3/developer_guides/forms/

解决方案2

当您真正想要使用简单的方法请求处理程序时,请使用此方法。注册自定义控制器和路由。

  1. 您可以在mysite / _config / routing.yml

    中指定路线
    ---
    Name: siteroutes
    ---
    Director:
      rules:
        processCustomForm: CustomFormController
    
  2. 处理您的请求

    class CustomFormController extends Controller
    {
        public function handleRequest( SS_HTTPRequest $request, DataModel $model ) {
            if (!$request->isPost()) {
              // handle invalid request
            }
    
            $name = $request->postVar('name')
            // process your form
        }
    }