jQuery表单库介绍
实现 html 中提交表单并实现不跳转页面处理返回值
jQuery表单库(jquery.form.js库)以jQuery为基础,用于处理表单AJAX提交,使得表单AJAX提交简单、容易,且能完整控制提交过程和处理结果,不需要任何特殊标签辅助,不影响原表单结构,只要使用该库就能使普通表单平滑升级为ajax提交表单。
官方地址:https://github/jquery-form/form
源代码查看和下载地址:https://github/jquery-form/form/blob/master/src/jquery.form.js
AjaxForm使用示例
1、导入js文件
需要导入相关的js文件。使用ajaxForm方式需要使用到jquery和jquery-form两个js文件。如:
<script type="text/javascript" src="/static/js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="/static/js/jquery.form.min.js"></script>
2、绑定表单
表单绑定它一般在$(document).ready(function () {}
里定义,它能让表单不刷新页面的情况下POST
到目标。如:
表单示例
<form id="editor_form" action="/api/editor/update" method="post">
<input type="hidden" name="id" value="3"/>
<input type="submit" value="提交">
</form>
JS示例
// wait for the DOM to be loaded
$(document).ready(function () {
// bind 'myForm' and provide a simple callback function
$('#editor_form').ajaxForm(function (message) {
var messageJson = JSON.parse(message);
if (messageJson.status == '0') {
alert("保存成功!");
} else {
alert("保存失败,请联系管理员!" + message);
}
});
});
3、运行效果
附:官方文档
Overview
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted. Submitting a form with AJAX doesn’t get any easier than this!
1 Add a form to your page. Just a normal form, no special markup required:
<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>
2 Include jQuery and the Form Plugin external script files and a short script to initialize the form when the DOM is ready:
<html>
<head>
<script src="http://ajax.googleapis/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github/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>
...
That’s it!
When this form is submitted the name and comment fields will be posted to comment.php. If the server returns a success status then the user will see a “Thank you” message.
更多推荐
【jQuery】使用jquery.form.js,获取提交表单返回值
发布评论