• jquery.form插件中动态修改表单数据


    jquery.form

    jquery.form插件(http://malsup.com/jquery/form/)是大家经常会用到的一个jQuery插件,它可以很方便将表单转换为ajax的方式进行提交。以下是官网给出的一个栗子:

    $(document).ready(function() {

    var options = {

    target: '#output1', // target element(s) to be updated with server response

    beforeSubmit: showRequest, // pre-submit callback

    success: showResponse // post-submit callback

    };

    $('#myForm1').ajaxForm(options);

    });

    function showRequest(formData, jqForm, options) {

    var queryString = $.param(formData);

    alert('About to submit: ' + queryString);

    return true;

    }

    function showResponse(responseText, statusText, xhr, $form) {

    alert('status: ' + statusText + ' responseText: ' + responseText +

    ' The output div should have already been updated with the responseText.');

    }

    再看以下需求:

    假设我想在用户点击submit按钮的时候,对表单中的某些数据进行动态的修改,例如要对密码字段进行加密处理,然后才发送给服务器。这时候,我们可能想到可以在beforeSubmit的回调函数(showRequest)中进行处理,例如像这个样子:

    function showRequest(formData, jqForm, options) {

    var jform = jqForm[0];

    var password= jform.password.value;

    password=encrypt(password); //加密密码

    $("#password").val(password);

    alert($("#password").val()); //检验一下输入框的内容是否发生了改变

    return true;

    }

    通过上面的代码,我们提交表单的时候很顺利弹出了我们期待的加密后的密码,表明表单内容已经被我们成功修改,但当我们以为一切都很顺利的时候,发现提交到服务器的密码依然是没有加密的密码?咋回事??

    原因是:我们的修改晚了!!

    因为,在执行beforeSubmit之前,jquery.form已经完成了表单数据的串行化处理,也就是说,你无论如何修改表单内容,其实都不影响串行化的结果。(就是jquery.ajax方法中的data数据)

    那么,有没有办法呢?当然有啦,因为jquery.form早就为我们准备了另一个回调接口:beforeSerialize

    我们只要将上述修改表单数据的过程挪到beforeSerialize的回调函数中,就可以在表单串行化之前对数据进行动态的修改。

    看一下官网的表述:

    • beforeSerialize

      Callback function to be invoked before the form is serialized. This provides an opportunity to manipulate the form before it's values are retrieved.

    • beforeSubmit

      Callback function to be invoked before the form is submitted. The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for validating the form data. If the 'beforeSubmit' callback returns false then the form will not be submitted.

    很清楚看到,beforeSerialize可以在表单的数值被获取之前对数据进行处理。而beforeSubmit则是在提交之前对已经获取的数据进行校验。

  • 相关阅读:
    梁祝(二胡独奏曲)
    《祝你一路顺风》-吴奇隆
    《祝你一路顺风》-吴奇隆(吉他谱)
    《少年王》片尾曲《白》——吴奇隆(简谱)
    《梁祝》-化蝶(五线谱)
    《西游记》--女儿情(简谱)
    cnn handwrite使用原生的TensorFlow进行预测
    tflearn 中文汉字识别,训练后模型存为pb给TensorFlow使用——模型层次太深,或者太复杂训练时候都不会收敛
    TensorFlow 图像预处理(一) 图像编解码,图像尺寸调整
    迁移学习算法之TrAdaBoost ——本质上是在用不同分布的训练数据,训练出一个分类器
  • 原文地址:https://www.cnblogs.com/zzt-lovelinlin/p/8086038.html
Copyright © 2020-2023  润新知