e.preventDefault在表单提交时被忽略

e.preventDefault being ignored on form submitting

本文关键字:表单提交 preventDefault      更新时间:2023-09-26

当我点击下面所示的任何按钮时,php页面getkey.php正被打开,而它不应该被打开,因为我使用的是e.preventDefault();id="getgame"与我的javascript代码中的相同。这让我很恼火,因为除了e.preventDefault();正在按预期运行。value="通过$_GET["appid"]传递,它以0作为1进行响应。

<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="112">Request</button>
</form>
<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="113">Request</button>
</form>
<form action="getkey.php" method="get" class="getgame">
<button name="appid" type="submit" value="114">Request</button>
</form>
 <script>
 $(function(){
$('form.getgame').on('submit', function(e){    
         // prevent native form submission here
    e.preventDefault();
    // now do whatever you want here
    $.ajax({
        type: $(this).attr('method'), // <-- get method of form
        url: $(this).attr('action'), // <-- get action of form
        data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
        beforeSend: function(){
            $('#result').html('');
        },
        success: function(data){
            $('#result').html(data);

 if(data === "0") {
 alert("foo");
  }
 if(data === "1") {
 alert("bar");
  }

             }
         });
     });     
 });
 </script>

首先,不能对多个元素使用相同的id。

将所有表单的id属性更改为class,如此

<form action="getkey.php" method="get" class="getgame">

然后在JS中,使用return false;而不是e.preventDefault()

像这个

$('form.getgame').on('submit', function(e){    
     //your ajax stuffs here
     return false;
});

注:jQuery serialize()不包括buttoninput[type=submit],因此您必须手动添加

所以你的JS看起来像

$(function(){
    $('form.getgame').on('submit', function(e){        
        // now do whatever you want here
        var appid = $(this).find("button[type=submit]").attr("value");
       $.ajax({
           type: $(this).attr('method'), // <-- get method of form
           url: $(this).attr('action'), // <-- get action of form
           data: { "appid" : appid }, // <-- serialize all fields into a string that is ready to be posted to your PHP file
           beforeSend: function(){
               $('#result').html('');
           },
           success: function(data){
               $('#result').html(data);
               if(data === "0") {
                   alert("foo");
               }
               if(data === "1") {
                   alert("bar");
               }
            }
        });    
       // prevent native form submission here
       return false;       
    });     
});