dongshengyin0147 2014-05-13 12:30
浏览 37
已采纳

通过JS提交表单不会通过jquery [duplicate]

This question already has an answer here:

I have a form in 'index.php`

<form action="" method="POST" id="myForm" name="myForm">
    <input type="text" name="myInput" id="myInput" maxlength="9" onChange="runOnce();" />
</form>

and in my JS code I have:

function runOnce() {
    var form = document.getElementById("myForm");
    form.submit();
}

and I also have the JS to handle the submission

$(document).ready(function() {
    $("#myForm").submit(function(event) {
         // prevent page refresh
         event.preventDefault();
         $.ajax({
             url: 'index.php',
             type: 'post',
             data: {
                 "myInput" : $('#myInput').val(), 
             },
             success: function(response) {
                 alert(response);
             }
         });
    });
});

and in my PHP section I have

if (isset($_POST["myInput"])) {
    // do something. . . 
}

The issue is that the page is still being refreshed even though i have event.preventDefault();

What am I doing wrong?

</div>
  • 写回答

1条回答 默认 最新

  • doumian3780 2014-05-13 12:34
    关注

    You could simply use:

    function runOnce() {
        $("#myForm").submit(); // this will trigger jQuery submit handler and so preventing default behaviour
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接