您的位置:首页 > Web前端 > JQuery

Jquery.Form 异步提交表单

2013-03-01 14:06 323 查看
1.在你的页面里写一个表单。一个普通的表单,不需要任何特殊的标记:

<formid="myForm"method="post"action="/Home/AjaxForm">

<div>

Name:<inputid="username"name="username"type="text"/> 

Password:<inputid="password"name="password"type="text"/>

<br/>

<inputtype="submit"value="submitasync"id="lnkSubmit"/>

</div>

</form>

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

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

<head>
<scripttype="text/javascript"src="path/to/jquery.js"></script>
<scripttype="text/javascript"src="path/to/form.js"></script>

<scripttype="text/javascript">
//waitfortheDOMtobeloaded
$(document).ready(function(){
//bind'myForm'andprovideasimplecallbackfunction

//为myform绑定ajaxForm异步提交事件,并提供一个简单的回调函数。
$('#myForm').ajaxForm(function(){
alert("Thankyouforyourcomment!");
});
});
</script>
</head>

[/code]
加上jquery.form组件后,提交表单时,页面不会再同步提交,而是由js做异步提交,因此提交后页面不会有刷新。

[/code]
3.加入能够与服务器端进行交互的回调函数。


?
//options是一个ajaxForm的配置对象。


?
?
?
?
?
?
?
?
服务端的代码如下

?

4.加入提交前的数据校验函数


为options对象添加beforeSubmit属性


?
?
验证用户名是否为空,是则提示输入,并取消表单提交。



1.使用post提交方式
2.构造表单的数格式
3.结合form表单的submit调用ajax的回调函数。
使用jQuery异步提交表单代码:
复制代码代码如下:
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title>
</head>
<scriptsrc="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);}
});
returnfalse;
});
});
</script>
<body>
<formid="f1"name="f1">
<inputname="a1"/>
<inputname="a2"/>
<inputid="File1"type="file"name="File1"/>
<inputid="Submit1"type="submit"value="submit"/>
</form>
</body>
</html>
如何异步跨域提交表单呢?
1.利用script的跨域访问特性,结合form表单的数据格式化,所以只能采用get方式提交,为了安全,浏览器是不支持post跨域提交的。
2.采用JSONP跨域提交表单是比较好的解决方案。
3.也可以动态程序做一代理。用代理中转跨域请求。
使用jQuery异步跨域提交表单代码:
复制代码代码如下:
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title>
</head>
<scriptsrc="js/jquery-1.4.2.js"></script>
<script>
jQuery(function($)
{
//使用jQuery异步跨域提交表单
$('#f1').submit(function()
{
$.getJSON("ta.aspx?"+$('#f1').serialize()+"&jsoncallback=?",
function(data)
{
alert(data);
});
returnfalse;
});
});
</script>
<body>
<formid="f1"name="f1">
<inputname="a1"/>
<inputname="a2"/>
<inputid="File1"type="file"name="File1"/>
<inputid="Submit1"type="submit"value="submit"/>
</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: