Cakephp 3.6:通过Ajax提交表单

时间:2019-02-26 15:19:04

标签: jquery ajax post cakephp submit

我有这个表格:

<?php
                    // Start a modal with a title, default value for 'close' is true
                    echo $this->Modal->create("My Modal Form", ['id' => 'exampleFormModalzz', 'close' => false]) ;

                    echo $this->Form->create($task, ['id' => 'newTaskForm']) ?>
                    <fieldset>
                        <legend><?= __('Add Task') ?></legend>
                        <?php
                             echo $this->Form->control('customer', ['id' => 'Autocomplete', 'empty' => false, 'required' => true]);
                             echo $this->Form->control('name', ['label' => 'Title','autocomplete' => 'off']);
                             echo $this->Form->control('instructions');
                             ?>
                    </fieldset>
                    <?php echo $this->Modal->end([  

                     $this->Form->submit(__('Direct Assign'), ['id' => 'DAbtn', 'name' => 'btn', 'class' => 'button' ]),
                     $this->Form->submit(__('Save as pending'), ['id' => 'SPbtn', 'name' => 'btn', 'class' => 'button' ]) 
                     ]); ?>

我想提交带有json数据的表单。所以我在jquery中尝试过:

<script type="text/javascript">
    $(document).ready(function(){
        $('#newTaskForm').submit(function(){
            var task = $(this).serialize();
            source: function( request, response ) {
                $.ajax({
                    type: "POST",
                    url: '/app/tasks/createTask',
                    datatype: 'json',
                    data: task,
                    success: function( data )
                    {

                    }
                });
            }

            return false;
        });
    });
</script> 

但是它一直通过邮寄请求邮寄表格。它不会通过ajax提交。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您可以将“提交”按钮替换为常规按钮,然后使用onClick调用ajax。

示例:

$this->Form->button('Direct Assign', ['id' => 'DAbtn', 'name' => 'btn', 'class' => 'button' ]);

在Ajax中:

$("#DAbtn").click(function () {
        var task = $("#newTaskForm").serialize();
        source: function( request, response ) {
            $.ajax({
                type: "POST",
                url: '/app/tasks/createTask',
                datatype: 'json',
                data: task,
                success: function( data )
                {

                }
            });
        }