【问题标题】:jquery.validate plugin accessing the form in ajax success callbackjquery.validate 插件在 ajax 成功回调中访问表单
【发布时间】:2012-06-12 03:56:52
【问题描述】:

我对如何使用 jQuery.validate 插件访问提交的表单感到困惑。

在API选项的“成功”选项中:http://jquery.malsup.com/form/#options-object

它说成功函数中的第 4 个参数是 jquery 包装的表单对象,但我尝试使用 jQuery 访问它时一直说是 undefined

这是成功函数在他们的示例页面上的外观:http://jquery.malsup.com/form/#ajaxSubmit

function showResponse(responseText, statusText, xhr, $form)  {
    var id=$form.attr('id');
    console.log('id:'+id);
}

不幸的是,console.log 显示Uncaught TypeError: Cannot call method 'attr' of undefined.

有什么想法吗?

谢谢, 时间

【问题讨论】:

  • 我认为您使用的是 jQuery () 中有一些注释,请参阅
  • @thecodeparadox,谢谢我使用 jQuery1.7.1。我看到了那张纸条,但不知道我是否误解了什么。

标签: javascript jquery jquery-validate


【解决方案1】:

我通过每次显式写出 jQuery 表单选择器而不是尝试将其作为对象传递来解决了这个问题。

所以我没有尝试绕过$form,而是使用了这个:

$('#myForm').attr(...)

它更冗长,但至少它有效!

【讨论】:

    【解决方案2】:

    我想该变量不能以$ 开头。删除$ 并重试?

    function showResponse(responseText, statusText, xhr, form)  {
        var id = form.attr('id');
        console.log('id:'+id);
    }
    

    或者这可能是另一种解决方案,如果不是 jQuery object:

    function showResponse(responseText, statusText, xhr, form)  {
        var id = $(form).attr('id');
        console.log('id:'+id);
    }
    

    其他可能性

    function showResponse(responseText, statusText, xhr, form)  {
        var id = $(form).attr('id');
        console.log('id:'+id);
    }
    function showResponse(responseText, statusText, xhr, form)  {
        var id = form.attr('id');
        console.log('id:'+id);
    }
    function showResponse(responseText, statusText, xhr, $form)  { // Won't work
        var id = form.attr('id');
        console.log('id:'+id);
    }
    function showResponse(responseText, statusText, xhr, $form)  { // High chance
        var id = $($form).attr('id');
        console.log('id:'+id);
    }
    

    希望这会有所帮助! :)

    【讨论】:

    • 还有更多的可能性,$() 包装和只是在$ 前面。让我们知道是否解决了问题。 :)
    • 你能把这些可能性放在你的答案中吗?我不确定你的意思
    • 是的,添加了我能想到的所有可能性。可能是$form 不会是 jQuery 对象,所以最后一种可能性是这样做的。试试看,让我们知道。 :)
    • 感谢您的尝试,但 form$form 均未定义。这里发生了一个更根本的问题
    • 当你调用函数showResponse时,你使用的是什么语法?您是否用正确的值填写了四个字段?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2023-03-03
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多