【问题标题】:jquery.form.js - How to get current form on submit?jquery.form.js - 如何在提交时获取当前表单?
【发布时间】:2014-08-15 16:31:29
【问题描述】:

我有这个标记

<form action="..." id="form1" class="foo">...</form>
<form action="..." id="form2" class="foo">...</form>
...

我有这个 Javascript 代码

$('.foo').ajaxForm({
    dataType: 'json',
    success: function (data) {
       // TODO: How do I get the form that triggered this?
       console.log( $(this) );
    }
});

正如您在 Javascript 代码中看到的,我想在何时获取当前表单元素 它提交并成功。输出$(this) 没有向我显示任何指向 到当前的表单元素。

如何在success函数中获取当前表单元素?

【问题讨论】:

  • 您想在提交时获取当前表单数据?你使用哪种编程语言@Backend?
  • @PratikJoshi 不是数据。我想要表单元素。
  • onClick() 可以调用在变量中设置表单ID的函数。

标签: javascript jquery ajax ajaxform


【解决方案1】:

假设您使用的是jQuery Form Plugin

你可以使用第四个参数

 success: function (data, statusText, xhr,  form ) {

References

success:表单提交后调用的回调函数。如果提供了“成功”回调函数,则在从服务器返回响应后调用它。它传递了以下参数:

  1. responseText 或 responseXML 值(取决于 dataType 选项的值)。
  2. 状态文本
  3. xhr(如果使用 jQuery
  4. jQuery 包装的表单元素(如果使用 jQuery

【讨论】:

  • 这正是我所需要的。谢谢!
【解决方案2】:

使用:

contextthis 传递给成功函数

检查以下链接:重复

$.ajax context option

How to pass Object context to jQuery.ajax JSONP callback?

【讨论】:

    【解决方案3】:

    使用beforeSubmit回调:

    beforeSubmit: function(arr, $form, options){
        options.context = $form;
    }
    

    这里的$form 是当前的表单,它正在被ajaxified,您可以使用options.context = $form; 将上下文添加到当前ajaxFormoptions。所以现在这将保存正在提交的当前表单,您可以获取当前上下文。


    类似这样的:

    $('.foo').ajaxForm({
       dataType: 'json',
       beforeSubmit: function(arr, $form, options){
        options.context = $form;
       },
       success: function (data) {
         // TODO: How do I get the form that triggered this?
         console.log( $(this) );
       }
    });
    

    【讨论】:

      【解决方案4】:

      你可以把你的代码改成这样:

      var fooForm = $('.foo');
      fooForm.ajaxForm({
          dataType: 'json',
          success: function (data) {
             // TODO: How do I get t
      
             console.log( fooForm);
          }
      });
      

      你不能得到 $(this) 因为在成功回调函数中, 'this' 指向窗户。

      其实你的代码可以写成这种风格:

      var fooForm = $('.foo');
      fooForm.ajaxForm({
          dataType: 'json',
          success: successCallback
      });
      function successCallback(data){
          //'this' point to window : ) 
          console.log( fooForm);
      
      }
      

      希望这会有所帮助。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-19
        • 2018-12-19
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多