簡體   English   中英

Ajax腳本不適用於CakePhp表單

[英]Ajax script not working on CakePhp form

所以我在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>

您應該從控制器返回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]); ?>

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM