如何发送带有提交事件的表单,而不是AJAX帖子

How to send the form with submit event instead of AJAX post?

本文关键字:帖子 AJAX 表单 何发送 提交 事件      更新时间:2023-09-26

我使用Yandex.Metrika来跟踪我网站上的用户活动(就像谷歌分析一样)。它有一个选项来跟踪用户如何使用html表单——他/她在那里输入了什么,在每个字段上花费了多少时间等等(俄语链接)。但为了正常工作,它需要提交带有submit事件的表单。

我有以下代码:

<form class="form-horizontal" role="form" id="utsDetails">
...
<button type="button" id="calc" name="calc">Calculate</button>
</form>
<script type="text/javascript">
   $("#calc").click(function() {
      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
           // all utsDetails form fields are there
        },          
        beforeSend: function(){
           // ...
        }
      })
      .done(function(data, textStatus, jqXHR) {
          // ...
      });

是否有任何方法可以修改我的代码以保持功能不变(即按下按钮时不应重新加载页面,结果应作为JSON接收,应执行beforeSenddone函数等),但使用submit发送表单数据?

以下更改帮助了我:

<form class="form-horizontal" role="form" id="utsDetails" method="POST" action="/"> <!-- added method and action -->
...
<button type="submit" id="calc" name="calc">Calculate</button> <!-- replaced  type with "submit" -->
</form>
<script type="text/javascript">
   $("#utsDetails").submit(function() { // instead of $("#calc").click(function() {
      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
           // all utsDetails form fields are there
        },          
        beforeSend: function(){
           // ...
        }
      })
      .done(function(data, textStatus, jqXHR) {
          // ...
      });
      return true; // to avoid page reload