jquery表单插件 jquery.form(异步提交)(学习总结)

摘要:
异步提交不是通过jquery实现的。表单。表单的目标位于名称˂!在iframe中通过iframe!
不通过jquery.form实现异步提交 通过一个iframe 将form 的target定位到iframe中的name
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form runat="server" target="ajaxiframe">
    <div>
        <input type="text" name="name1" value="111111111" />
    </div>
    <input type="submit" value="submit" />
    </form>
    <iframe name="ajaxiframe" style="display:none"></iframe>
</body>
</html>
 
 

  // 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
        type:      'get'        // 'get' or 'post', override for form's 'method' attribute
 
        // 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 是一个数组,这里通过$.param将它转换成一个字符串
    // formData的格式 将input控件以josn的格式串过来
    // [
    //     { name:  username, value: valueOfUsernameInput },
    //     { name:  password, value: valueOfPasswordInput }
    // ]
    //
     for (var i=0; i < formData.length; i++) {
         alert("formDataName:"+ formData[i].name);
    }
   
   //var usernameValue = $('input[name=name1]').val();
   var usernameValue = $('input[name=name1]').fieldValue();
  alert("usernameValue:"+usernameValue);
   
    var queryString = $.param(formData);
    alert("formData:"+formData);
   
    //jqForm是一个将form中的元素装载在里面的对象,通过 var formElement = jqForm[0];  读取dom元素
    var form = jqForm[0]; //不能出现两个name相同的
    alert(form.name1.value);

    // 如果返回false将阻止页面提交
    //返回除了false外的任何其他都会提交form
    return true;
}
 
// post-submit callback (返回信息,返回状态)
function showResponse(responseText, statusText)  {
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}

beforeSubmit:  showRequest,  //接收3个参数()

success:       showResponse  // 接收2个参数(1.返回数据,2.返回状态)

beforeSubmit后的3个参数的解释

Form Markup: <form action="dummy.php" method="post">
    Username: <input type="text" name="username" />
    Password: <input type="password" name="password" />
    <input type="submit" value="Submit" />
</form>First, we initialize the form and give it a beforeSubmit callback function - this is the validation function. // prepare the form when the DOM is ready
$(document).ready(function() {
    // bind form using ajaxForm
    $('#myForm2').ajaxForm( { beforeSubmit: validate } );
});
 
Validate Using the formData ArgumentUsername:  Password:   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:
    // formData 的格式
    // [
    //     { 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.');
}
 
Validate Using the jqForm ArgumentUsername:  Password:  
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.');
}
 
Validate Using the fieldValue MethodUsername:  Password:  
 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框架应用]:form.js官方插件介绍

Form插件,支持Ajax,支持Ajax文件上传,功能强大,基本满足日常应用。

1、JQuery框架软件包下载

jquery表单插件 jquery.form(异步提交)(学习总结)第1张
文件:jquery.rar
大小:29KB
下载:下载

2、Form插件下载
jquery表单插件 jquery.form(异步提交)(学习总结)第1张
文件:jquery.form.rar
大小:7KB
下载:下载



3、Form插件的简单入门
第一步:先增加一个表单

<formid="myForm"action="comment.php"method="post">
Name:<inputtype="text"name="name"/>
Comment:<textareaname="comment"></textarea>
<inputtype="submit"value="Submit Comment"/>
</form>

第二步:jquery.js和form.js文件的包含

<head>
<scripttype="text/javascript"src="path/to/jquery.js"></script>
<scripttype="text/javascript"src="path/to/form.js"></script>
<scripttype="text/javascript">
// 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>

3、Form插件的详细使用方法及应用实例

http://www.malsup.com/jquery/form/

============================
该插件的作者在介绍form.js时,说了这样的一句话:

Submitting a form with AJAX doesn't get any easier than this!

表单插件API


英文原文:
http://www.malsup.com/jquery/form/#api

表单插件API提供了几个方法,让你轻松管理表单数据和进行表单提交。

ajaxForm

增加所有需要的事件监听器,为AJAX提交表单做好准备。ajaxForm不能提交表单。在document的ready函数中,使用ajaxForm来 为AJAX提交表单进行准备。ajaxForm接受0个或1个参数。这个单个的参数既可以是一个回调函数,也可以是一个Options对象。
可链接(Chainable):可以。

实例:

$('#myFormId').ajaxForm();


ajaxSubmit

马上由AJAX来提交表单。大多数情况下,都是调用ajaxSubmit来对用户提交表单进行响应。ajaxSubmit接受0个或1个参数。这个单个的参数既可以是一个回调函数,也可以是一个Options对象。
可链接(Chainable):可以。

实例:
// 绑定表单提交事件处理器
$('#myFormId').submit(function() {
// 提交表单
$(this).ajaxSubmit();
// 为了防止普通浏览器进行表单提交和产生页面导航(防止页面刷新?)返回false
return false;
});


formSerialize

将表单串行化(或序列化)成一个查询字符串。这个方法将返回以下格式的字符串:name1=value1&name2=value2
可链接(Chainable):不能, 这个方法返回一个字符串。

实例:
var queryString = $('#myFormId').formSerialize();

// 现在可以使用$.get、$.post、$.ajax等来提交数据
$.post('myscript.php', queryString);

fieldSerialize

将表单的字段元素串行化(或序列化)成一个查询字符串。当只有部分表单字段需要进行串行化(或序列化)时,这个就方便了。这个方法将返回以下格式的字符串:name1=value1&name2=value2
可链接(Chainable):不能,这个方法返回一个字符串。

实例:
var queryString = $('#myFormId .specialFields').fieldSerialize();


fieldValue

返回匹配插入数组中的表单元素值。从0.91版起,该方法将总是以数组的形式返回数据。如果元素值被判定可能无效,则数组为空,否则它将包含一个或多于一个的元素值。
可链接(Chainable):不能,该方法返回数组。

实例:
// 取得密码输入值
var value = $('#myFormId :password').fieldValue();
alert('The password is: ' + value[0]);


resetForm

通过调用表单元素原有的DOM方法,将表单恢复到初始状态。
可链接(Chainable):可以。

实例:
$('#myFormId').resetForm();


clearForm

清除表单元素。该方法将所有的文本(text)输入字段、密码(password)输入字段和文本区域(textarea)字段置空,清除任何select元素中的选定,以及将所有的单选(radio)按钮和多选(checkbox)按钮重置为非选定状态。
可链接(Chainable):可以。

$('#myFormId').clearForm();


clearFields

清除字段元素。只有部分表单元素需要清除时才方便使用。
可链接(Chainable):可以。

$('#myFormId .specialFields').clearFields();


Options对象

ajaxForm和ajaxSubmit都支持众多的选项参数,这些选项参数可以使用一个Options对象来提供。Options只是一个JavaScript对象,它包含了如下一些属性与值的集合:

target

指明页面中由服务器响应进行更新的元素。元素的值可能被指定为一个jQuery选择器字符串,一个jQuery对象,或者一个DOM元素。
默认值:null。

url

指定提交表单数据的URL。
默认值:表单的action属性值

type

指定提交表单数据的方法(method):“GET”或“POST”。
默认值:表单的method属性值(如果没有找到默认为“GET”)。

beforeSubmit

表单提交前被调用的回调函数。“beforeSubmit”回调函数作为一个钩子(hook),被提供来运行预提交逻辑或者校验表单数据。如果 “beforeSubmit”回调函数返回false,那么表单将不被提交。“beforeSubmit”回调函数带三个调用参数:数组形式的表单数 据,jQuery表单对象,以及传入ajaxForm/ajaxSubmit中的Options对象。表单数组接受以下方式的数据:

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]


默认值:null

success

表单成功提交后调用的回调函数。如果提供“success”回调函数,当从服务器返回响应后它被调用。然后由dataType选项值决定传回responseText还是responseXML的值。
默认值:null

dataType

期望返回的数据类型。null、“xml”、“script”或者“json”其中之一。dataType提供一种方法,它规定了怎样处理服务器的响应。这个被直接地反映到jQuery.httpData方法中去。下面的值被支持:

'xml':如果dataType == 'xml',将把服务器响应作为XML来对待。同时,如果“success”回调方法被指定, 将传回responseXML值。

'json':如果dataType == 'json', 服务器响应将被求值,并传递到“success”回调方法,如果它被指定的话。

'script':如果dataType == 'script', 服务器响应将求值成纯文本。


默认值:null(服务器返回responseText值)

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".
布尔标志,表示数据是否必须严格按照语义顺序(slower?)来进行提交。注意:一般来说,表单已经按照语义顺序来进行了串行化(或序列化),除了 type="image"的input元素。如果你的服务器有严格的语义要求,以及表单中包含有一个type="image"的input元素,就应该将 semantic设置为true。(译注:这一段由于无法理解,翻译出来可能语不达意,但请达人指正。)
默认值:false

resetForm

布尔标志,表示如果表单提交成功是否进行重置。
Default value: null

clearForm

布尔标志,表示如果表单提交成功是否清除表单数据。
默认值:null

实例:

// 准备好Options对象
var options = {
target:     '#divToUpdate',
url:        'comment.php',
success: function() {
alert('Thanks for your comment!');
} };

// 将options传给ajaxForm
$('#myForm').ajaxForm(options);


注意:Options对象还可以用来将值传递给jQuery的$.ajax方法。如果你熟悉$.ajax所支持的options,你可以利用它们来将Options对象传递给ajaxForm和ajaxSubmit。

免责声明:文章转载自《jquery表单插件 jquery.form(异步提交)(学习总结)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇百度地图API图标、文本、图例与连线Rotate Matrix 旋转矩阵性质分析下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

FormData使用方法详解

FormData的主要用途有两个: 1、将form表单元素的name与value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率。 2、异步上传文件 一、创建formData对象 1、创建一个空对象: //通过FormData构造函数创建一个空对象 var formdata=new FormData(); //可以通过append(...

jQuery源码学习之一 (采用匿名函数自执行模式)

1、如何在jquery官网找到 bug的相关说明?       打开网址  http://bugs.jquery.com/  后,再搜索框中输入bug的 编号(在jquery源码的注释中找到,例如:“ #13335 ”),可找到相关的详细说明和评论。 2、jquery应用 匿名函数自执行模式(避免全局变量污染) (function( window,...

单文件文件上传到服务器(HTML5+js+Java)

上传单文件到服务器 应公司要求,在HTML5页面上实现上传文件到服务器,对于一个还没毕业的实习生菜鸟来说,这可不得了-----不会,网上各种百度,找各种博客还是没解决,最后还是请教了公司的大神,人家给卸了一个例子,然后根据人家写的终于把这个上传文件搞定。 好了,开始上代码。 HTML5代码: <form name="upform"action="...

jquery获取元素内容-text()和val()

不传参数的text()方法在获取文本内容时,会把子元素的文本也获取过来(会删除 HTML 标记),例子: <!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> &l...

JavaScript与jquery的对比

  javascript jQuery 入口函数 只能有一个,如果有多个,后面的会覆盖前面 可以有多个,并且不会发生覆盖的情况 代码容错性 代码容错性差,代码出现错误,会影响到后面代码的运行。 代码容错性好,屏蔽错误,并且不会影响后面代码的运行 浏览器兼容性 兼容性差,比如火狐不支持innerText 对浏览器兼容性做了封装,因此不存在兼...

Jquery学习---Easy UI 框架

Jquery的easyui 1.1. easyui的目录分析 以 jquery Easy UI 1.3.2 版本学习 demo 实例 locale 国际化信息 plugins 框架一些插件 src 源码 themes 样式文件 easyloader.js  框架核心加载器 (加载其它plugin) jquery-1.8.0.min.js  jQuery...