我有一个模态形式的表单,可以将数据保存在表格(食物)中。该表具有以下字段:


ID
类别
类型


当我加载页面时,我立即得到一个Uncaught SyntaxError: Unexpected identifier (managefood:393);我在下面的代码中对此行进行了注释。

打开模式并填写字段可以正常工作。但是,保存失败,刷新页面并检查MySQL后,未输入新数据。我不太确定如何检查我的AJAX POST失败的位置(例如,如果表单输入之一已损坏,并且由于必须填写这些字段,这将说明无法保存)。

我也将表的Model再次进行了Cake烘焙,只是为了检查Model中是否存在问题,但这并不能解决问题。

下面的代码包括打开模式的按钮和脚本,带有表单输入的模式本身以及保存数据的脚本。



$(document).ready(function() {
  $("#newsavebutton").click(function() {
    $.post("<?= $host . $basepath ?>/food/add.json", {
      category: $('#category').val(),
      type: $('#type').val() //line 393
    };);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<button onclick="newFood()" class="btn btn-primary btn-xl page-scroll wow tada">New Food</button>

<script>
  function newFood() {
    $('#newfoodModal').modal('show');
  }
</script>

<div class="modal fade" id="newfoodModal" tabindex="-1" role="dialog" aria-labelledby="newfoodLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                     <span aria-hidden="true">&times;</span>
                    </button>
        <h3 class="modal-title" id="newfoodLabel">New Food</h3>
        <br>
        <div>
          <div class="col-sm-12">
            <label for="category" id="newCategoryLabel" style="text-align: left">Category</label>
            <select name="category" id="newCategory" onchange="newchangeCategory()" class="form-control">
                                <option value="" disabled selected hidden>Select a category</option>
                                <option value="Fruit">Fruit</option>
                                <option value="Vegetable">Vegetable</option>
                            </select>
          </div>
          <div class="col-sm-12">
            <label for="type" id="newTypeLabel" style="text-align: left">Type</label>
            <select name="type" id="newType" class="form-control"></select>
          </div>

          //this script enables for the second select to change based on the first - if Fruit is chosen as the category for example, only fruit options are shown in the Type select.
          <script type="text/javascript">
            var typeOptions = {};
            typeOptions['Fruit'] = [
              'Apple',
              'Pear',
              'Banana',
              'Plum',
              'Peach'
            ];
            typeOptions['Vegetable'] = [
              'Broccoli',
              'Carrot',
              'Pumpkin'
            ];

            function newchangeCategory() {
              var categoryChoice = document.getElementById('newCategory');
              var typeChoice = document.getElementById('newType');
              var selectedCategoryChoice = categoryChoice.options[categoryChoice.selectedIndex].value; //line 340
              console.log(selectedCategoryChoice);
              while (typeChoice.options.length) {
                typeChoice.remove(0);
              }
              var typesAvailable = typeOptions[selectedCategoryChoice];
              if (typesAvailable) {
                var i;
                for (i = 0; i < typesAvailable.length; i++) {
                  var type = new Option(typesAvailable[i], typesAvailable[i]);
                  typeChoice.options.add(type);
                }
              }
            };
          </script>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close
                    </button>
        <button id="newsavebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes
                    </button>
      </div>
    </div>
  </div>
</div>





以下也是Controller中Add函数的代码:

public function add()
    {
        $food = $this->Food->newEntity();
        if ($this->request->is('post')) {
            $food = $this->Food->patchEntity($food, $this->request->data);
            if ($this->Food->save($food)) {
                $this->Flash->success(__('The food has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The food could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('food'));
        $this->set('_serialize', ['food']);
    }

最佳答案

据我所见,这是一个语法错误。
您的代码如下:

$.post("<?= $host . $basepath ?>/food/add.json", {
  category: $('#category').val()
  type: $('#type').val() //line 393
};);


尝试在,属性声明之前的第392行之后添加逗号type:。像这样:

$.post("<?= $host . $basepath ?>/food/add.json", {
  category: $('#category').val(), //<-- here
  type: $('#type').val() //line 393
};);


关于错误处理问题:根据jQuery documentation,您可以使用.done().fail().always()方法来查看POST请求本身是否成功。例如:

$.post("<?= $host . $basepath ?>/food/add.json", {
  category: $('#category').val(), //<-- here
  type: $('#type').val() //line 393
})
.done(function(data) {
    console.log(data);
    alert( "success" );
  })
.fail(function(error) {
    console.log(error);
    alert( "error" );
});


这样,您可以看到POST返回什么以及erorr是什么(如果有)。

07-28 02:47
查看更多