Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript SilverStripe通过Ajax提交HTML表单_Javascript_Php_Jquery_Ajax_Silverstripe - Fatal编程技术网

Javascript SilverStripe通过Ajax提交HTML表单

Javascript SilverStripe通过Ajax提交HTML表单,javascript,php,jquery,ajax,silverstripe,Javascript,Php,Jquery,Ajax,Silverstripe,我想通过Ajax将数据从简单的HTML表单传递到控制器,然后处理数据并返回响应 目前,我有以下几点: 主页.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkform(this);"> <!-- Text input--> <div class="form-group"> <label class="col-m

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

目前,我有以下几点:

主页.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>
(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);
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';
        }
    }
}
<?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
        }
    }

}
在开发工具中,我可以看到我得到了带有404NotFound错误的xhr processForm


如何让这个Ajax表单在SilverStripe控制器上正常工作?

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

当您发送请求POST/processForm时,它被视为页面并由ModelAsController管理。这就是为什么会出现404错误-没有URLSEMENT=processForm的SiteTree记录

解决方案1

使用表单对象。它在运行时自动创建所有路由配置。阅读更多

解决方案2

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

  • 您可以在mysite/_config/routing.yml中指定路由

    ---
    Name: siteroutes
    ---
    Director:
      rules:
        processCustomForm: CustomFormController
    
  • 处理你的请求

    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
        }
    }
    
  • 蜘蛛

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

    Page.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';
            }
        }
    }
    
    <?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
            }
        }
    
    }
    

    Spidey,可能存在一些问题:-需要在控制器中为您的方法指定$allowed\u actions-可能需要在SilverStripe中执行表单以获取SecurityToken,但我不是100%同意:)一个简单而完整的例子对我和任何处于相同情况的人来说都是非常好的。@Spidey,并将此表单用作页面模板中的$MyForm。这个答案是更好的实现,请接受它。