Ajax脚本无法在CakePhp表单上运行

时间:2017-05-26 08:21:51

标签: javascript ajax cakephp cakephp-3.0

所以我在add.ctp动作中有这个代码,我希望它在提交这个表单后加载另一个div,但是因为我对CakePHP3和Ajax很新,所以我无法弄清楚是什么让脚本无法工作,我的页面上的jQuery工作正常,但脚本中的日志不会显示在控制台中。我可能会遗漏一些非常明显的东西,但我要求你的东西。

      <?php
      echo $this->Form->create($article, ['id' => 'ajaxform']);
      echo $this->Form->input('title',array('class'=`enter code here`>'form-control'));
      echo $this->Form->input('body', ['rows' => '3','class'=>'form-control']);
      echo '<p></p>';
      echo $this->Form->button(__('Salvar artigo'),array('class'=>'btn btn-success', 'id' => 'butao'));
      echo $this->Form->end();
      ?>


      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script type="text/javascript">
      console.log("test");
      $(document).ready(function(){
        $('#butao').click(function(e){
          console.log("teste2");
          $("#ajaxform").submit();
          e.preventDefault;
            $(".content-wrapper").load("main #main");
        });

        $("#ajaxform").on('submit',function(e)
        {
          console.log("teste");
            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");
            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR)
                {
                  $('#main').html(data);
                    //data: return data from server
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    //if fails
                }
            });
            e.preventDefault(); //STOP default action
            e.unbind(); //unbind. to stop multiple form submit.
        });

        $("#ajaxform").submit(); //Submit  the FORM


      });
      </script>

ArticlesController:

public function add()
{
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $article = $this->Articles->patchEntity($article, $this->request->getData());
        // Added this line
        $article->user_id = $this->Auth->user('id');
        // You could also do the following
        //$newData = ['user_id' => $this->Auth->user('id')];
        //$article = $this->Articles->patchEntity($article, $newData);
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('Your article has been saved.'));
            return $this->redirect(['action' => 'main']);
        }
        $this->Flash->error(__('Unable to add your article.'));
    }
    $this->set('article', $article);
}

- EDIT-- 我的主页面代码添加

<?php foreach ($articles as $article): ?>
  <tr>
      <td><?= $article->id ?></td>
      <td>
          <?= $this->Html->link($article->title, ['action' => 'view', 
$article->id]) ?>
      </td>
      <td>
          <?= $article->created->format(DATE_RFC850) ?>
      </td>
      <td>
            <?= $this->Form->postLink(
                'Apagar',
                ['action' => 'delete', $article->id],
                ['confirm' => 'Têm a certeza?','class'=>'btn-danger btn-sm'])

            ?>
          <?= $this->Html->link('Editar', ['action' => 'edit', $article->id],array('class'=>'btn-warning btn-sm')) ?>
          <?= $this->Html->link('Copiar', ['action' => 'copy', $article->id],array('class'=>'btn-warning btn-sm')) ?>
      </td>
  </tr>
  <?php endforeach; ?>
</table>
</div>
<button id="add" class="btn btn-primary btn-xs">
    <h6>Adicionar Artigo</h6>
    <script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
    <script>
    $(document).ready(function(){
      $('#add').click(function(){
          $("#main").load("add #addctp");
      });
    });
    </script>
  </button>

1 个答案:

答案 0 :(得分:0)

您应该从控制器返回一个json。

为此:

app/Config/routes.php添加:

Router::extensions(['json']);

启用json扩展名。

在你的控制器中添加:

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

启用内容类型的自动视图类切换。

$this->set('article', $article);更改为:

$this->set(compact('article'));
$this->set('_serialize', ['article']);

如果您在将数据转换为json/xml之前不需要执行任何自定义格式设置,则可以跳过定义控制器操作的视图文件。

现在您可以使用json扩展名请求ArticlesController::add(),然后您的操作会将$article序列化为json。

最后创建app/webroot/js/Articles.js

Articles = {
    init: function () {
        this.add();
    },

    add: function(){
        $( "#ajaxform" ).submit(function( event ) {

            var that    = $(this),
                data    = that.serializeArray(),
                formURL = $('#ajaxform').attr('action') + '.json';

            event.preventDefault();

            $.ajax(
            {
                url: formURL,
                dataType: 'JSON',
                type: 'POST',
                data: data,
                success: function(data,text,xhr)
                {
                    console.log(data);
                },
                error: function()
                {

                },
                complete: function ()
                {

                }
            });


        });
    }
};

$(document).ready(function () {
    Articles.init();
});

并在您的观点中加入:

<?= $this->Html->script('Articles', ['block' => true]); ?>

另见: