php Ajax 和 jquery 表单加载然后提交不起作用


php Ajax and jquery form loading then submission not working

我在testmain中有4个文件testmain.php test1.php test2.php test3.php,在testmain中.php我有一个带有类"content_load"的div,我正在逐个单击加载3个文件,它们加载正常,但是test1.php是完成加载时的表单文件 我正在使用ajax提交它,但它正在重定向,我从昨天开始尝试但无法解决这个问题, 如果我不使用 ajax 加载文件而只提交 test1.php那工作正常,但是当我使用 load() 组合加载文件的代码并使用 $.ajax() 提交时,加载文件的代码工作正常,但请重定向任何解决此问题,以便我可以继续学习。

测试主.php

 <div id="menu_top">
                <a class="menu_top" href="test1.php">TEST 1</a> /
                <a class="menu_top" href="test2.php">TEST 2</a> /
                <a class="menu_top" href="test3.php">TEST 3</a> /
    </div>
        <div class="content_load"></div>    

测试1.php

 <form class="ajax" action="test1.php" method="post" enctype="multipart/form-data">
        <input type="text" name="txt1" /> <br>
        <input type="text" name="txt2" /> <br>
        <select name="sel">
        <?php
        include  '../mysql_connect.php';
        $db = new DBConfig();
        $conn = $db->getDbPDO();
       $sql = "SELECT * FROM tbl_campus ORDER BY camp_id ASC";
       //$sql = "SELECT camp_id FROM tbl_campus ORDER BY camp_id ASC";
       $query = $conn->query($sql);
       $result = $query->fetchAll(PDO::FETCH_ASSOC);
       $arrlength = count($result);
       for ($x = 0; $x < $arrlength; $x++){
       ?>        
       <option value="<?php echo $result[$x]['camp_id']; ?>"><?php echo $result[$x]['camp_name']; ?>
       <?php } ?>
        </select>
        <br><br>
        <input type="submit" value="Click" name="submit" />
    </form>

test2.php & test 3.php

  <h3>THIS IS TEST 2</h3>   <h3>THIS IS TEST 2</h3>

j查询文件

$(document).ready(function() {            
$('.content_load').load($('.menu_top:first').attr('href'));
$('.menu_top').click(function(){
    var page = $(this).attr('href');
    $('.content_load').load(page); return false; });
    $('form.ajax').on('submit', function(e){
     e.preventDefault();
        var that = $(this);
url = that.attr('action'), type = that.attr('method'), data = {};
        that.find('[name]').each(function(index, value){            
        var that=$(this),
            name = that.attr('name'),
            value = that.val();
            data[name] = value;
    });
    $.ajax({
       url: url,
       type: type,
       data: data,
       success: function(response){
           console.log(response);
       }
    });
    clearAll();
    return false;
              });
});
function clearAll(){
    $("form :input").each(function(){
       $(this).val(""); 
    });
}

不能对尚未加载的元素使用直接事件处理程序。只需尝试更改此行:

$('form.ajax').on('submit', function(e){

自:

$('.content_load').on('submit','form.ajax', function(e){

否则,JavaScript 不会将该事件绑定到表单,并且会发生常规submit

这里区别的很好的解释:直接与委托 - jQuery .on()

我可能误解了这个问题,但如果您提交网站将执行表单操作。如果你不想这样,你需要在提交时添加"return false",或者做一个"按钮",没有"输入"来提交。