本文介绍了SilverStripe通过Ajax提交HTML表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to pass data from a simple HTML form to a controller through Ajax, then process the data and return a response back.

目前我有以下:

HomePage.ss

<form method="POST" class="form-horizontal submit-form" onsubmit="return checkform(this);">

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="name">Name</label>
        <div class="col-md-8">
            <input id="name" name="name" type="text" placeholder="insert full Name" class="form-control input-md" required="" />
        </div>
    </div>

    <!-- Button -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="send-btn"></label>
        <div class="col-md-8">
            <button id="send-btn" name="send-btn" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>

JavaScript

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

HomePage.php

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';
        }
    }
}

在我看到的开发者工具中我得到了xhr processForm,找不到404错误。

In developer tools I can see that I got the xhr processForm with a 404 not found error.

如何让这个Ajax表单与SilverStripe控制器一起正常工作?

How do I get this Ajax form working correctly with the SilverStripe controller?

推荐答案

蜘蛛,

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

I've done something similar to below. This is a quick and dirty demo and hasn't been tested, but it may get you going in the right path. If you're unfamiliar with how forms work within SilverStripe there is a lesson for front end forms in SilverStripe. I've found the lessons useful personally and provide the code for the lesson as well: 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);

这篇关于SilverStripe通过Ajax提交HTML表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:16