AJAX 表单提交 文件上传
1. AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。提高用户体验度。
主要是使用XMLHttpRequest 对象
<script type="text/javascript" >
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//读取状态
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = xmlhttp.responseText;//
//Text <h1>successMessage</h1> 直接使用
//Json {'data':'success'} 自动解析为script对象 使用data.data=='success'
//XML <?xml encoding="UTF-8">
// <title>无题<title>
// </xml>
//data.documentElement.getElementsByTagName("title")[0].firstChild.nodeValue == '无题'
document.getElementById("txtHint").innerHTML=data;
}
}
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");// 可选值
xmlhttp.open("GET","/ajax/Test.action?data=HelloWorld",true);
xmlhttp.send();
</script>
请求状态readyState 0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
2.Jquery 提供了对AJAX的封装。使用将简便了。开发更简单了。
$.ajax() $.get(), $.post() $.post(){ urlString: 'test.action',//发送请求地址。 data: {"key":"value","key2","value2"},//或者使用$("#formId").serialize()序列化 (可选)Map待发送 Key/value 参数。 callback:function(){alert("OK!");},(可选)Function发送成功时回调函数。 //type (可选)String返回内容格式,xml, html, script, json, text, _default。 success:function(msg) { alert("success"+msg.data);//json } error:function(result) { alert("error!"); } }
3当表单中存在file属性,需要用到文件上传时就会出问题了。这里需要用到jquery.form.js插件。
var mainform = $("#formId"); mainform.ajaxSubmit({ type: 'post', url: "hello/formTest.action" , beforeSend: function (a, b, c){$("#showMsg").value('正在保存数据中...');},//展示 “正在保存数据” complete: function (){ $("#showMsg").hide()},//隐藏 “正在保存数据” success: function(data){ alert("success"+data.data); }, error: function(result){ alert("error"); } });
灵活运动ajax可以提高用户体验度。不过要传递数据量较大时最好不要使用。消耗时间太多反而体验变差。
Stay Hungry,Stay Foolish!
浙公网安备 33010602011771号