jQuery插件 -- Form表单插件jquery.form.js

  jquery.form.js官网

  jQuery Form插件是一个优秀的Ajax表单插件,可以非常容易地、无侵入地升级HTML表单以支持Ajax。jQuery Form有两个核心方法 -- ajaxForm() 和 ajaxSubmit(), 它们集合了从控制表单元素到决定如何管理提交进程的功能。另外,插件还包括其他的一些方法: formToArray()、formSerialize()、fieldSerialize()、fieldValue()、clearForm()、 clearFields() 和 resetForm()等。

  通过该插件,我们可以非常简单的实现表单的异步提交,并实现文件上传、进度条显示等等。

<script type="text/javascript">
$(function(){
    var options = { 
       // target:        '#output',   //把服务器返回的内容放入id为output的元素中  
        beforeSubmit:  showRequest,  //提交前的回调函数  
        success:       showResponse, //提交后的回调函数  
        resetForm: true, 
        dataType:  'json' 
 
        // other available options: 
        //url:       url          //默认是form的action, 如果申明,则会覆盖  
        //type:      type       //默认是form的method(get or post),如果申明,则会覆盖  
        //dataType:  null         //html(默认), xml, script, json...接受服务端返回的类型  
        //clearForm: true        //成功提交后,清除所有表单元素的值   
        //resetForm: true         //成功提交后,重置所有表单元素的值  
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 ////限制请求的时间,当请求大于3秒后,跳出请求  
    }; 
 
    // bind to the form's submit event 
    $('#my_form').submit(function() { 
        $(this).ajaxSubmit(options); 
        return false;  //阻止表单默认提交  
    }); 
});
// pre-submit callback 
function showRequest(formData, jqForm, options) { 
   //formData: 数组对象,提交表单时,Form插件会以Ajax方式自动提交这些数据,格式如:[{name:user,value:val },{name:pwd,value:pwd
  //jqForm:   jQuery对象,封装了表单的元素    
  //options:  options对象 
    /*
    var uname = $("#uname").val();
    if(uname==""){
        $("#msg").html("姓名不能为空!");
        return false;
    }
    
    var age = $("#age").val();
    if(age==""){
        $("#msg").html("年龄不能为空!");
        return false;
    }*/
    $("#msg").html("正在提交...");
    
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    $("#msg").html('提交成功');
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    alert('status: ' + statusText + '

responseText: 
' + responseText.msg + 
        '

The output div should have already been updated with the responseText.'); 
}
</script>  
原文地址:https://www.cnblogs.com/hehaiyang/p/4716680.html