Jquery.Form 异步提交表单

1. 在你的页面里写一个表单。一个普通的表单,不需要任何特殊的标记:

<form id="myForm" method="post" action="/Home/AjaxForm">
<div>
Name:<input id="username" name="username" type="text" /> &nbsp;
Password:<input id="password" name="password" type="text" />
<br />
<input type="submit" value="submit async" id="lnkSubmit" />
</div>
</form>

在没有Jquery.Form组件的时候,提交表单,页面会进入阻塞模式,等待服务器端的响应。

2. 引入jQuery和Form Plugin Javascript脚本文件并且添加几句简单的代码让页面在DOM加载完成后初始化表单:

<head> 
    <script type="text/javascript" src="path/to/jquery.js"></script> 
    <script type="text/javascript" src="path/to/form.js"></script> 
 
    <script type="text/javascript"> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            // 为myform绑定ajaxForm异步提交事件,并提供一个简单的回调函数。
            $('#myForm').ajaxForm(function() { 
                alert("Thank you for your comment!"); 
            }); 
        }); 
    </script> 
</head>
 
加上jquery.form组件后,提交表单时,页面不会再同步提交,而是由js做异步提交,因此提交后页面不会有刷新。
 
3. 加入能够与服务器端进行交互的回调函数。
?
1
$(document).ready( function () {
                  //options是一个ajaxForm的配置对象。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    var options = {
        //target: '#output1',   // target element(s) to be updated with server response
        //beforeSubmit: showRequest,  // pre-submit callback
       <font color= "#ff0000" > success: callBackFunc  // post-submit callback</font>
        // 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'
    $( '#myForm' ).ajaxForm(options);
});
?
1
// responseText是服务端的响应值。statusText是页面
?
1
2
3
4
5
// 提交状态值,success表示成功。
function callBackFunc(responseText, statusText) {
    if (statusText == 'success' ) {
        alert(responseText);
    }
?
1
else {
?
1
alert(“服务端错误!”);
?
1
2
     }
}
?
1
如果返回的是json数据则回调函数可以这么写
?
1
2
3
4
5
6
7
8
9
10
11
12
13
function resultFunction(responseText,statusText) {
        if (statusText == 'success' ) {
            if (responseText.code == 1) {
                alert(responseText.message);
            }
            else {
                alert( 'error occurs!' );
            }
        }
        else {
            alert( '服务器错误!' );
        }
    }

服务端的代码如下

?
1
2
3
4
5
6
7
[HttpPost]
public ActionResult AjaxForm(FormCollection form)
{
    string message = "Name:" + form[ "username" ] + " PWD: " +form[ "password" ]  ;
    //return Content(message);
    return Json( new { code = 1, message = message });
}
 
4. 加入提交前的数据校验函数
 
为options对象添加 beforeSubmit属性
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var options = {
                //target: '#output1',   // target element(s) to be updated with server response
                <font color= "#ff0000" >beforeSubmit: checkData,  // pre-submit callback
</font>                success: callBackFunc  // 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
            };
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// pre-submit callback
       function checkData(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;
           if ($(formElement).find( "#username" ).val() == "" ) {
               alert( "please enter username!" );
               return false ;
           } else {
               return true ;
           }
       }
验证用户名是否为空,是则提示输入,并取消表单提交。
 
 

1.使用post提交方式 2.构造表单的数格式 3.结合form表单的submit调用ajax的回调函数。 使用 jQuery 异步提交表单代码: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>无标题页</title> </head> <script src="js/jquery-1.4.2.js"></script> <script> jQuery(function($) { // 使用 jQuery 异步提交表单 $('#f1').submit(function() { $.ajax({ url: 'ta.aspx', data: $('#f1').serialize(), type: "post", cache : false, success: function(data) {alert(data);} }); return false; }); }); </script> <body> <form id="f1" name="f1"> <input name="a1" /> <input name="a2" /> <input id="File1" type="file" name="File1"/> <input id="Submit1" type="submit" value="submit" /> </form> </body> </html>

如何异步跨域提交表单呢? 1.利用script 的跨域访问特性,结合form表单的数据格式化,所以只能采用get方式提交,为了安全,浏览器是不支持post跨域提交的。 2.采用JSONP跨域提交表单是比较好的解决方案。 3.也可以动态程序做一代理。用代理中转跨域请求。 使用 jQuery 异步跨域提交表单代码: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>无标题页</title> </head> <script src="js/jquery-1.4.2.js"></script> <script> jQuery(function($) { // 使用 jQuery 异步跨域提交表单 $('#f1').submit(function() { $.getJSON("ta.aspx?"+$('#f1').serialize()+"&jsoncallback=?", function(data) { alert(data); }); return false; }); }); </script> <body> <form id="f1" name="f1"> <input name="a1" /> <input name="a2" /> <input id="File1" type="file" name="File1"/> <input id="Submit1" type="submit" value="submit" /> </form> </body> </html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值