【问题标题】:Ajax script not working on CakePhp formAjax 脚本不适用于 CakePhp 表单
【发布时间】:2017-05-26 08:21:51
【问题描述】:

所以我的 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);
}

--编辑-- 我要添加的主页代码

<?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>

【问题讨论】:

  • 您的表单操作在哪里?
  • 在我的控制器中。

标签: javascript ajax cakephp cakephp-3.0


【解决方案1】:

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

为此:

app/Config/routes.php 中添加:

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

启用 json 扩展。

在你的控制器中添加:

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

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

$this-&gt;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]); ?>

另见:

【讨论】:

  • 不知道是不是因为CakePHP3但是Router::parseExtensions('json');给出错误:调用未定义的方法 Cake\Routing\Router::parseExtensions() 并将代码放入无限循环中。
  • 对不起,CakePHP 2.x 的答案我已经写好了,我会更新的。
  • $this->set('_serialize', ['article'])); parentesis 中的语法错误,如果我把它取下来,它会给我错误:无法取消设置字符串偏移量。
  • @DanielPereira 已修复
  • 将您的实际代码作为问题信号的一部分添加为编辑
猜你喜欢
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多