插件jQuery.form.js。支持ajax表单提交和ajax文件上传。
jq插件官网地址:http://plugins.jquery.com/
插件在线教程及示例:http://jquery.malsup.com/form/#getting-started
一、开始使用(get started)
1、jq库,和jq.form.js插件的引用
2、定义一个具有id的表单
3、表单的提交:
1)action,method。可以 以表单属性的形式书写:(<form id="fm" action="a.php" method="post"></form>)。
$(document).ready(function() {
var options = {
success:function(){} showResponse // post-submit callback
};
$('#myForm1').ajaxForm(options);
});
2)也可以以参数的形式写入:
$(document).ready(function() {
var options = {
type:"POST" ,
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: a.php // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#myForm1').ajaxForm(options);
});
![]()
二、表单插件的函数(方法):(API)
ajaxForm-
- 增加所有需要的事件监听器,为ajax提交表单做准备。ajaxForm并不能提交表单。在document的ready函数中,使用ajaxForm来为ajax提交表单进行准备。
- Prepares a form to be submitted via AJAX by adding all of the necessary event listeners. It does not submit the form. Use
ajaxForm in your document's ready function to prepare your form(s) for AJAX submission. ajaxForm takes zero or one argument. The single argument can be either a callback function or an Options Object.
Chainable: Yes.
Note: You can pass any of the standard
$.ajax options to ajaxForm
Example:
$('#myFormId').ajaxForm();
ajaxSubmit- 使用ajax提交表单。
- Immediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form.
ajaxSubmit takes zero or one argument. The single argument can be either a callback function or an Options Object.
Chainable: Yes.
Note: You can pass any of the standard
$.ajax options to ajaxSubmit
Example:
// attach handler to form's submit event
$('#myFormId').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});
formSerialize- 将表单串行化(或序列化)为一个查询字符串。这个方法将返回以下格式的字符串:name1=value1&name2=value2。
- Serializes the form into a query string. This method will return a string in the format:
name1=value1&name2=value2
Chainable: No, this method returns a String.
Example:
var queryString = $('#myFormId').formSerialize();
// the data could now be submitted using $.get, $.post, $.ajax, etc
$.post('myscript.php', queryString);
fieldSerialize- 将表单的字段元素串行化(或序列化)为一个查询字符串。当只有部分表单字段需要进行串行化(或序列化)时,使用这个就很方便了。返回以下格式的字符串:name=value1&name2=value2。
- Serializes field elements into a query string. This is handy when you need to serialize only part of a form. This method will return a string in the format:
name1=value1&name2=value2
Chainable: No, this method returns a String.
Example:
var queryString = $('#myFormId .specialFields').fieldSerialize();
fieldValue- 返回匹配插入数组中的表单元素值。该方法以数组的形式返回数据。如果元素值被判定可能无效,则数组为空。
- Returns the value(s) of the element(s) in the matched set in an array. As of version .91, this method always returns an array. If no valid value can be determined the array will be empty, otherwise it will contain one or more values.
Chainable: No, this method returns an array.
Example:
// get the value of the password input
var value = $('#myFormId :password').fieldValue();
alert('The password is: ' + value[0]);
resetForm- Resets the form to its original state by invoking the form element's native DOM method.
Chainable: Yes.
Example:
$('#myFormId').resetForm();
clearForm- 将表单恢复到初始状态。清空所有的输入框、下拉框,取消选中单选框和复选框
- Clears the form elements. This method emptys all of the text inputs, password inputs and textarea elements, clears the selection in any select elements, and unchecks all radio and checkbox inputs.
Chainable: Yes.
$('#myFormId').clearForm();
clearFields- 清空,部分指定的表单字段
- Clears field elements. This is handy when you need to clear only a part of the form.
Chainable: Yes.
$('#myFormId .specialFields').clearFields();
三、方法ajaxForm and ajaxSubmit 的参数(Options)。两者的参数及用法如下:
- 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. The
beforeSerialize function is invoked with two arguments: the jQuery object for the form, and the Options Object passed into ajaxForm/ajaxSubmit.
beforeSerialize: function($form, options) {
// return false to cancel submit
}
Default value: null - beforeSubmit
- 表单提交前被调用的回调函数。如果回调函数返回false表单将不被提交。回调函数带三个调用参数:数组形式的表单数据,jQuery表单对象,以及传入ajaxForm/ajaxSubmit中的Options对象。
- 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. The 'beforeSubmit' callback is invoked with three arguments: the form data in array format, the jQuery object for the form, and the Options Object passed into ajaxForm/ajaxSubmit.
beforeSubmit: function(arr, $form, options) {
// The array of form data takes the following form:
// [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
// return false to cancel submit
}
Default value: null - clearForm
- 表示如果表单提交成功是否清除表单数据。
- Boolean flag indicating whether the form should be cleared if the submit is successful
Default value: null
- data
- An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
- dataType
- 回调函数,接收的数据格式
- Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The
dataType option provides a means for specifying how the server response should be handled. This maps directly to the jQuery.httpData method. The following values are supported:
'xml': if dataType == 'xml' the server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value
'json': if dataType == 'json' the server response will be evaluted and passed to the 'success' callback, if specified
'script': if dataType == 'script' the server response is evaluated in the global context
Default value: null
- error
- Callback function to be invoked upon error.
- forceSync
- Boolean value. Set to true to remove short delay before posting form when uploading files (or using the iframe option). The delay is used to allow the browser to render DOM updates prior to performing a native form submit. This improves usability when displaying notifications to the user, such as "Please Wait..."
Default value: false
Added in v2.38
- iframe
- Boolean flag indicating whether the form should always target the server response to an iframe.
This is useful in conjuction with file uploads. See the File Uploads
documentation on the Code Samples page for more info.
Default value: false
- iframeSrc
- String value that should be used for the iframe's src attribute when/if an iframe is used.
Default value: about:blank
Default value for pages that use https protocol: javascript:false
- iframeTarget
- Identifies the iframe element to be used as the response target for file uploads. By default, the plugin
will create a temporary iframe element to capture the response when uploading files. This options allows you
to use an existing iframe if you wish. When using this option the plugin will make no attempt at handling
the response from the server.
Default value: null
Added in v2.76
- replaceTarget
- Optionally used along with the the
target option. Set to true if the
target should be replaced or false if only the target contents should
be replaced.
Default value: false
Added in v2.43
- resetForm
- Boolean flag indicating whether the form should be reset if the submit is successful
Default value: null
- semantic
- Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the
normal form serialization is done in semantic order with the exception of input elements of
type="image".
You should only set the semantic option to true if your server has strict semantic requirements
and your form contains an input element of type="image".
Default value: false
- success
- 表单成功提交后调用的回调函数。然后dataType选项值决定传回responseText还是responseXML的值
- Callback function to be invoked after the form has been submitted.
If a 'success' callback function is provided it is invoked after the response has been returned
from the server. It is passed the following arguments:
- 1.) responseText or responseXML value (depending on the value of the dataType option).
- 2.) statusText
- 3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
- 4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Default value: null
- target
- 指明页面中由服务器响应进行更新的元素。元素的值可能被指定为一个jQuery选择器字符串、一个jquery对象、一个DOM元素。
- Identifies the element(s) in the page to be updated with the server response.
This value may be specified as a jQuery selection string, a jQuery object,
or a DOM element.
Default value: null
- type
- The method in which the form data should be submitted, 'GET' or 'POST'.
Default value: value of form's method attribute (or 'GET' if none found)
- uploadProgress
-
Callback function to be invoked with upload progress information (if supported by the browser).
The callback is passed the following arguments:
- 1.) event; the browser event
- 2.) position (integer)
- 3.) total (integer)
- 4.) percentComplete (integer)
Default value: null
- url
- 指定提交表单数据的URL。
- URL to which the form data will be submitted.
Default value: value of form's action attribute
Example:
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);