单击提交按钮时,提交带有 jquery/AJAX 的表单不起作用

Submiting a form with jquery/AJAX isn't working when clicking the submit button

我正在尝试使用 jquery/AJAX 提交表单,但是当我单击提交按钮时我的函数从未被调用。

我的网站是这样的: CarMenu.php

<html lang="en">
<html>
<head>
   <meta charset="ISO-8859-1">
   <title>ArsenalAutoBrokers - Backend - add car</title>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css"     type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
   <link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
   <link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
   <script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
   <script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
   <script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
   <script charset="UTF8" src="../js/app/carForm.js"></script>
   <script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
   <div id="container">
      <div id="leftMenuContainer">
         <ul id="menu">
            <li id="addCarItem">Add car</li>
            <li id="saveCarItem">Edit cars</li>
         </ul> 
      </div>
      <div id="rightMainContent">

      </div>
      <div class="clear"></div>
    </div>
  </body>
</html>

在该页面上,我正在使用 jquery 菜单并将数据加载到 ID 为 'rightMainContent' 的 div。

执行此操作的 javascript 代码如下所示:carForm.js

$(document).ready(function () {
   $( "#menu" ).menu({
    select: function(event, ui) {
        if (ui.item.attr('id') === 'addCarItem') {
           $("#rightMainContent").load(
             '/CarDealer/CarForm/CreateCar/AddCar.php');       
        }
    }
});  
});

如果您单击 'addCar' 菜单项,网站的部分内容将从该 php 网站加载:

 <script type="text/javascript">

 $('input[type=submit]').button();
 //$('#activeCheck').button();
 $("#activeCheck").attr('checked','checked');
 $('#saveButton').hide();
 $('#tabs').tabs();
 $('#accordion' ).accordion({heightStyle: "content"});

 $('#tabs').tabs({
     activate: function (event, ui) {
         var act = $("#tabs").tabs("option", "active");
         if (act == 0 || act == 1) {
            $('#saveButton').hide();
         } else {
            $('#saveButton').show();
         }
     }
 });  

 $('#fileToUpload').on('change', function(){ 
   var fileSelect = document.getElementById('fileToUpload');
   var files = fileSelect.files;

   if (files.length > 10) {
     $('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
     $('.info').show();
   } else {
        $('.info').html('');
     $('.info').hide();
   }

 });

 </script>

 <form id="carSaveForm"
    action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
    enctype="multipart/form-data">
    <div id="tabs">
        <ul>
            <li><a href="#tabsGen">General Car Information</a></li>
            <li><a href="#tabsDescr">Car Descriptions</a></li>
            <li><a href="#tabsPics">Picture Upload</a></li>
        </ul>
        <div id="tabsGen">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
   </div>
        <div id="tabsDescr">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
   </div>
        <div id="tabsPics">
    <?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>

   </div>
    </div>
    <br> <input id="saveButton" type="submit" name="submit" value="save" />
 </form>    

该站点仅包含输入按钮、文件选择器等表单元素

嗯,到目前为止一切顺利。一切都正常显示,但如果我单击提交按钮,则不会调用此函数:addCar.js

$('#carSaveForm').on('submit', function(event){
        event.preventDefault();

        var formData = new FormData();
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        formData.append('carBrand'               , $('input[name=carBrand]').val());
        formData.append('carModelYear'           , $('input[name="carModelYear"]').val());
        formData.append('carModel'               , $('input[name=carModel]').val());
        formData.append('carTrim'                , $('input[name="carTrim"]').val());
        formData.append('carDriveTrain'          , $('input[name="carDriveTrain"]').val());
        formData.append('carCondition'           , $('input[name="carCondition"]').val());
        formData.append('carType'                , $('input[name="carType"]').val());
        formData.append('carFuelType'            , $('input[name="carFuelType"]').val());
        formData.append('carTransmission'        , $('input[name="carTransmission"]').val());
        formData.append('carEngine'              , $('input[name="carEngine"]').val());
        formData.append('carCylinder'            , $('input[name="carCylinder"]').val());
        formData.append('carMileage'             , $('input[name="carMileage"]').val());
        formData.append('carExteriorColor'       , $('input[name="carExteriorColor"]').val());
        formData.append('carInteriorColor'       , $('input[name="carInteriorColor"]').val());
        formData.append('carLocation'            , $('input[name="carLocation"]').val());
        formData.append('carVin'                 , $('input[name="carVin"]').val());
        formData.append('carStock'               , $('input[name="carStock"]').val());
        formData.append('carPrice'               , $('input[name="carPrice"]').val());
        formData.append('carPriceDetails'        , $('input[name="carPriceDetails"]').val());
        formData.append('carTax'                 , $('input[name="carTax"]').val());
        formData.append('carTaxDetails'          , $('input[name="carTaxDetails"]').val());
        formData.append('carCurrency'            , $('input[name="carCurrency"]').val());
        formData.append('carOnline'              , $('input[name="carOnline"]').val());
        formData.append('carDescr'               , $('input[name="carDescr"]').val());
        formData.append('carBodyDescr'           , $('input[name="carBodyDescr"]').val());
        formData.append('carDriveTrainDescr'     , $('input[name="carDriveTrainDescr"]').val());
        formData.append('carExteriorDescr'       , $('input[name="carExteriorDescr"]').val());
        formData.append('carElectronicsDescr'    , $('input[name="carElectronicsDescr"]').val());
        formData.append('carSaftyFeaturesDescr'  , $('input[name="carSaftyFeaturesDescr"]').val());
        formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());

        var fileSelect = document.getElementById('fileToUpload');
        var files = fileSelect.files;
        // Loop through each of the selected files.
        for (var i = 0; i < files.length; i++) {
          var file = files[i];

          // Add the file to the request.
          formData.append('files[]', file, file.name);
        }

        // process the form
        $.ajax({
           type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
           url         : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
           data        : formData, // our data object
           contentType: false,
           processData: false,
           success: function (data) {
               $('.success').fadeIn(200).show();
               $('.error').fadeOut(200).hide();
           },
           error: function (data) {
               $('.success').fadeIn(200).hide();
               $('.error').fadeOut(200).show();
           }

        });
        return false;
    });

我不知道为什么这个函数永远不会被调用,我已经尝试了所有方法,我在谷歌上搜索了很多但我没有得到它。我整天都在搜索错误,但我看不到它。

请帮助我。

感谢您的帮助。

提前致谢。

$('#carSaveForm').on('submit', function(event)更改为$('#carSaveForm').on('click','#saveButton', function(event)

从 CarMenu.php

中剪切 (ctrl+x) 这一行
<script charset="UTF8" src="../js/app/addCar.js"></script>

并将脚本粘贴 (ctrl+v) AddCar.php

jQuery 仅在页面运行时识别页面中的元素,因此 jQuery 无法识别添加到 DOM 的新元素。为了对抗这种情况,请使用 event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

例如,此按钮已通过 AJAX 添加到 DOM:

<input id="saveButton" type="submit" name="submit" value="save" />

为了正确处理这个(如果它是唯一添加到页面的表单)是委托点击或提交事件:

$(document).on('click', '#saveButton', function(event) {...

此外,如果您继续添加此处所示的表单,您的页面中将出现重复的 ID,并且 id's must be unique。不能使它们独一无二将导致许多问题。

确保在浏览器的控制台中查看 AJAX 请求/响应 as outlined here 以查找并更正您可能遇到的错误。