【问题标题】:How to send the form with submit event instead of AJAX post?如何发送带有提交事件而不是 AJAX 帖子的表单?
【发布时间】:2014-11-11 01:53:44
【问题描述】:

我使用 Yandex.Metrika 来跟踪我网站上的用户活动(就像 Google Analytics 一样)。它有一个选项来跟踪用户如何使用 html 表单 - 他/她在那里输入的内容、每个字段花费了多少时间等 (link in Russian)。但是为了正常工作,它需要提交带有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发送表单数据?

【问题讨论】:

  • 你尝试绑定提交事件而不是点击?像 $("#utsDetails").submit(function() ... 而不是 $("#calc").click(function() {
  • 什么意思?发送POST 和提交表单时一样吗?

标签: javascript html forms form-submit yandex-metrika


【解决方案1】:

以下更改帮助了我:

<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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    相关资源
    最近更新 更多