-
jQuery Form Plugin
-
原文地址:http://jquery.malsup.com/form/
- Getting Started
- API
- Options
- Examples
- Form Fields
- FAQ
- Download
概观
jQuery表单插件允许您轻松而不显眼地升级HTML表单以使用 AJAX 。主要方法,ajaxForm
并
ajaxSubmit
从表单元素收集信息,以确定如何管理提交过程。这两种方法都支持多种选项,使您可以完全控制数据的提交方式。
用AJAX提交表单并没有比这更容易!
快速入门指南
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
</head>
...
而已!
提交此表单时,名称和注释字段将被发布到comment.php。如果服务器返回成功状态,则用户将看到“谢谢”消息。
表单插件API
表单插件API提供了几种方法,可以让您轻松管理表单数据和表单提交。-
通过添加所有必要的事件侦听器来准备要通过
AJAX
提交的表单。它并
没有
提交表单。使用
ajaxForm
您的文档ready
功能来准备您的表单提交AJAX。ajaxForm
采取零或一个参数。单个参数可以是回调函数或 Options Object。
连锁:是的。注意:您可以将任何标准
$.ajax
选项传递 给ajaxForm例:
$('#myFormId').ajaxForm();
-
立即通过AJAX提交表单。在最常见的用例中,这是为了响应用户单击表单上的提交按钮而调用的。
ajaxSubmit
采取零或一个参数。单个参数可以是回调函数或 Options Object。
连锁:是的。注意:您可以将任何标准
$.ajaxoptions
参数传递给ajaxSubmit例:
// 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; });
-
将表单序列化为查询字符串。这个方法将返回一个字符串格式:可
name1=value1&name2=value2
连接:不,这个方法返回一个字符串。例:
var queryString = $('#myFormId').formSerialize(); // the data could now be submitted using $.get, $.post, $.ajax, etc $.post('myscript.php', queryString);
-
将字段元素序列化为查询字符串。当你只需要序列化表单的一部分时,这是很方便的。这个方法将返回一个字符串格式:可
name1=value1&name2=value2
连接:不,这个方法返回一个字符串。例:
var queryString = $('#myFormId .specialFields').fieldSerialize();
-
返回数组中匹配集合中元素的值。从版本.91开始,这个方法
总是
返回一个数组。如果没有有效的值可以确定数组将是空的,否则将包含一个或多个值。
可链接:不,这个方法返回一个数组。例:
// get the value of the password input var value = $('#myFormId :password').fieldValue(); alert('The password is: ' + value[0]);
-
通过调用表单元素的本地
DOM
方法将表单重置为其原始状态 。
连锁:是的。例:
$('#myFormId').resetForm();
-
清除表单元素。此方法清空所有文本输入,密码输入和textarea元素,清除所有选择元素中的选择,并取消选中所有广播和复选框输入。
连锁:是的。$('#myFormId').clearForm();
-
清除字段元素。当你只需要清除表格的一部分时,这很方便。
连锁:是的。$('#myFormId .specialFields').clearFields();
ajaxSubmit
formSerialize
fieldSerialize
fieldValue
resetForm
clearForm
clearFields
ajaxForm and ajaxSubmit Options
注意:除了下面列出的选项,您还可以将任何标准选项传递 给ajaxForm和ajaxSubmit。 $.ajax
ajaxForm
并
ajaxSubmit
支持可使用一个可选参数对象提供多种选择。Options对象只是一个JavaScript对象,它包含的属性值设置如下:
例:
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
请注意,选项对象也可以用来传递值给jQuery的 $.ajax
方法。如果您熟悉您所支持的选项,则$.ajax
可以在传递给ajaxForm
和 的选项对象中使用它们ajaxSubmit
。
代码示例
以下代码控制它下面的HTML表单。它用来ajaxForm
绑定表单并演示如何使用提交前和提交后的回调。
// prepare the form when the DOM is ready
$(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
// other available options:
//url: url // 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
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
alert('About to submit: \n\n' + queryString);
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property
// if the ajaxForm 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 ajaxForm 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 + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
输出Div(#输出1):
以下代码控制它下面的HTML表单。它ajaxSubmit
用来提交表单。
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // 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
};
// bind to the form's submit event
$('#myForm2').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);
// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];
alert('About to submit: \n\n' + queryString);
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// 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 + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
输出Div(#输出2):
这个页面给出了几个例子,说明表单数据在发送到服务器之前如何验证。秘密在beforeSubmit
选择。如果这个预先提交的回调返回false,则提交进程被中止。
以下登录表单用于以下每个示例。每个示例都将验证用户填写的用户名和密码字段。
表格标记:
<form id="validationForm" action="dummy.php" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
首先,我们初始化表单并给它一个beforeSubmit
回调函数 - 这是验证函数。
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#myForm2').ajaxForm( { beforeSubmit: validate } );
});
使用formData
参数进行验证
function validate(formData, jqForm, options) {
// formData is an array of objects representing the name and value of each field
// that will be sent to the server; it takes the following form:
//
// [
// { name: username, value: valueOfUsernameInput },
// { name: password, value: valueOfPasswordInput }
// ]
//
// To validate, we can examine the contents of this array to see if the
// username and password fields have values. If either value evaluates
// to false then we return false from this method.
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
使用jqForm
参数进行验证
function validate(formData, jqForm, options) {
// jqForm is a jQuery object which wraps the form DOM element
//
// To validate, we can access the DOM elements directly and return true
// only if the values of both the username and password fields evaluate
// to true
var form = jqForm[0];
if (!form.username.value || !form.password.value) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}
使用fieldValue
方法验证
function validate(formData, jqForm, options) {
// fieldValue is a Form Plugin method that can be invoked to find the
// current value of a field
//
// To validate, we can capture the values of both the username and password
// fields and return true only if both evaluate to true
var usernameValue = $('input[name=username]').fieldValue();
var passwordValue = $('input[name=password]').fieldValue();
// usernameValue and passwordValue are arrays but we can do simple
// "not" tests to see if the arrays are empty
if (!usernameValue[0] || !passwordValue[0]) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}
注意
您可以在 jQuery插件页面 上找到专门处理字段验证的jQuery插件。此页面显示如何处理从服务器返回的JSON数据。
下面的表单向服务器提交消息,服务器以JSON格式回显消息。
表格标记:
<form id="jsonForm" action="json-echo.php" method="post">
Message: <input type="text" name="message" value="Hello JSON" />
<input type="submit" value="Echo as JSON" />
</form>
服务器代码在
json-echo.php
:
<?php echo '{ "message": "' . $_POST['message'] . '" }'; ?>
JavaScript的:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#jsonForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
});
});
回调函数
function processJson(data) {
// 'data' is the json object returned from the server
alert(data.message);
}
此页面显示如何处理从服务器返回的XML数据。
下面的表格向服务器提交消息,服务器以XML格式回显消息。
表格标记:
<form id="xmlForm" action="xml-echo.php" method="post">
Message: <input type="text" name="message" value="Hello XML" />
<input type="submit" value="Echo as XML" />
</form>
服务器代码在
xml-echo.php
:
<?php
// !!! IMPORTANT !!! - the server must set the content type to XML
header('Content-type: text/xml');
echo '<root><message>' . $_POST['message'] . '</message></root>';
?>
JavaScript的:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#xmlForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'xml',
// success identifies the function to invoke when the server response
// has been received
success: processXml
});
});
回调函数
function processXml(responseXML) {
// 'responseXML' is the XML document returned by the server; we use
// jQuery to extract the content of the message node from the XML doc
var message = $('message', responseXML).text();
alert(message);
}
此页面显示如何处理从服务器返回的HTML数据。
下面的表单向服务器提交消息,服务器在HTML div中回显。响应添加到htmlExampleTarget
下面的div中的这个页面。
表格标记:
<form id="htmlForm" action="html-echo.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
服务器代码在
html-echo.php
:
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
JavaScript的:
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
htmlExampleTarget(输出将在下面添加):
这个页面演示了表单插件的文件上传功能。没有特殊的编码需要处理文件上传。文件输入元素会自动检测并为您处理。
支持XMLHttpRequest Level 2的浏览器 将能够无缝地上传文件,甚至可以在上传过程中获得进度更新。对于较老的浏览器,使用涉及iframe的回退技术,因为不可能使用XMLHttpRequest对象的1级实施上传文件。这是一种常见的回退技术,但它有固有的局限性。iframe元素被用作表单提交操作的目标,这意味着服务器响应被写入iframe。如果响应类型是HTML或XML,那么这很好,但如果响应类型是脚本或JSON,那么这两个函数通常都不包含需要在HTML标记中使用实体引用来重复使用的字符。
为了解决使用iframe模式时脚本和JSON响应的挑战,表单插件允许将这些响应嵌入到textarea
元素中,建议您在与文件上传和较旧的浏览器结合使用时对这些响应类型执行此操作。
需要注意的是,即使dataType选项设置为'script',并且服务器实际上是用一些javascript对多部分表单提交作出响应,应该强制响应的Content-Type标题text/html
,否则Internet Explorer将提示用户下载一个“文件”。
另外请注意,如果表单中没有文件输入,那么请求使用普通的XHR来提交表单(而不是iframe)。这会让你的服务器代码的负担知道什么时候使用textarea,什么时候不使用textarea。如果你喜欢,你可以使用iframe
插件的选项强制它总是使用iframe模式,然后你的服务器总是可以将响应嵌入到textarea中。但推荐的解决方案是测试“X-Requested-With”请求头。如果这个头的值是'XMLHttpRequest',那么你知道表单是通过ajax发布的。以下PHP片段显示了如何确保成功返回内容:
<?php
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr)
echo '<textarea>';
?>
// main content of response here
<?php
if (!$xhr)
echo '</textarea>';
?>
下面的表单提供了一个类型为“file”的输入元素以及一个select元素来指定响应的dataType。提交的表单 files.php
使用dataType来确定返回的响应类型。
与领域一起使用
本页面描述并演示了表单插件fieldValue
和
fieldSerialize
方法。
fieldValue方法
fieldValue
允许您检索字段的当前值。例如,要在ID为“myForm”的表单中检索密码字段的值,可以这样写:
var pwd = $('#myForm :password').fieldValue()[0];
这个方法
总是
返回一个数组。如果没有有效的值可以确定数组将是空的,否则将包含一个或多个值。
fieldSerialize这个
fieldSerialize
允许您将表单的子集序列化为查询字符串。当您只需要处理某些字段时,这非常有用。例如,要仅序列化表单的文本输入,您可以编写:
var queryString = $('#myForm :text').fieldSerialize();
[1] http://www.w3.org/TR/html4/interact/forms.html#successful-controls。
默认情况下,fieldValue
并fieldSerialize
在“成功控制”的唯一功能。这意味着如果您在未选中的复选框上运行以下代码,结果将是一个空数组。
// value will be an empty array if checkbox is not checked:
var value = $('#myUncheckedCheckbox').fieldValue();
// value.length == 0
但是,如果您确实想知道复选框元素的“值”,即使未选中,您也可以这样写:
// value will hold the checkbox value even if it's not checked:
var value = $('#myUncheckedCheckbox').fieldValue(false);
// value.length == 1
经常问的问题
-
什么版本的jQuery是与表格插件兼容?
- 表单插件与jQuery v1.5及更高版本兼容。 表单插件是否有其他插件的依赖?
- 没有。 表单插件是否快速?它准确地序列化表单吗?
- 是! 查看我们的 比较页面 ,了解Form Plugin与其他库(包括Prototype和dojo)的比较。 什么是便捷的方式来使用表格插件?
-
ajaxForm
提供了最简单的方法来使您的HTML表单使用AJAX。这是准备表格的一站式购物方法。 -
这些方法有两个主要区别:
ajaxSubmit
提交表格,ajaxForm
不。当您ajaxSubmit
立即调用它时,会将表单数据序列化并将其发送到服务器。当你调用ajaxForm
它时,将必要的事件监听器添加到表单中,以便它可以检测用户提交表单的时间。当发生这种情况ajaxSubmit
是为你而调用的。- 当使用
ajaxForm
提交的数据时,将包括提交元素的名称和值(或者如果提交元素是图像,则其点击坐标)。
我怎样才能取消表单提交?
- 您可以通过添加“beforeSubmit”回调函数并从该函数返回false来阻止提交表单。有关示例,请参见代码示例页面。 是否有一个单元测试套件的表格插件?
- 是! 表单插件有一套广泛的测试用来验证其功能。 运行单元测试。 表单插件是否支持文件上传?
- 是! 为什么不是我所有的输入值都发布了?
- jQuery表单序列化与HTML规范密切相关。只有 成功的控件 才能提交。 如何显示上传进度信息?
- 演示
ajaxForm
和之间有什么区别
ajaxSubmit
?
下载
官方表单插件可以在这里找到:jquery.form.js或从插件的Github仓库。
缩小版本: jquery.form.min.js
支持
通过 jQuery Google组 可以获得对插件的支持 。这是许多jQuery开发人员和用户订阅的一个非常活跃的组织。
贡献者
Form Plugin的开发是一个社区的努力,许多人提供了想法和代码。下面的人有这样或那样的贡献:
- 约翰Resig
- 迈克·阿尔苏普
- 马克警员
- 克劳斯·哈特尔
- 马特·格林
- 耶胡达·卡茨
- JörnZaefferer
- Sam Collett
- Gilles van den Hoven
- 凯文Glowacz
- Alex Andrienko
如果我忘记了某人,请给我发电子邮件。