正确使用jQuery验证插件的submitHandler方法

时间:2022-12-01 09:04:28

first a little bit of documentation from the jQuery validation plugin:

首先来自jQuery验证插件的一些文档:

"Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the validation isn't triggered again."

“使用submitHandler来处理某些内容然后使用默认提交。请注意,”form“指的是DOM元素,这样就不会再次触发验证。”

submitHandler: function(form) {
    $.ajax({
        type: 'POST',
        url: form.action,
        data: 'current_password=' + form.current_password + '&new_password=' + form.new_password,
        success: function(){
            alert("succes");
        }
    });
}

So, naturally my ingenious piece of code isn't working. I'm trying to access the 'action' attribute and the two input fields from the form object, with no luck. How am I supposed to do this?

所以,我的巧妙代码自然不起作用。我正试图从表单对象访问'action'属性和两个输入字段,没有运气。我该怎么做?

1 个解决方案

#1


8  

Try this instead:

试试这个:

submitHandler: function(form) {
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: { current_password : form.current_password.value,
                new_password: form.new_password.value }
        success: function(){
            alert("succes");
        }
    });
}

Currently instead of submitting the values of the elements it's literally calling a toString on them, so just add .value to get the values. Also we're passing data as an object here so it gets encoded, otherwise if for example the password had a & in it, the post wouldn't be correct.

目前,不是提交元素的值,而是在字面上调用toString,因此只需添加.value即可获取值。此外,我们将数据作为对象传递到此处,以便对其进行编码,否则,如果密码中包含&,则帖子将不正确。

#1


8  

Try this instead:

试试这个:

submitHandler: function(form) {
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: { current_password : form.current_password.value,
                new_password: form.new_password.value }
        success: function(){
            alert("succes");
        }
    });
}

Currently instead of submitting the values of the elements it's literally calling a toString on them, so just add .value to get the values. Also we're passing data as an object here so it gets encoded, otherwise if for example the password had a & in it, the post wouldn't be correct.

目前,不是提交元素的值,而是在字面上调用toString,因此只需添加.value即可获取值。此外,我们将数据作为对象传递到此处,以便对其进行编码,否则,如果密码中包含&,则帖子将不正确。