异步交互过程是在后台进行,页面不需要刷新,交互过程中如果没有提示信息,用户会无所适从,甚至容易产生误解。为了避免此类问题,在设计过程中建议增加动态提供信息,指导用户操作。
【示例】
-
服务器端请求文件
//test.asp <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%> <% dim data data = Request.QueryString("data") Response.AddHeader "Content-Type","text/html;charset=gb2312" Response.Write data %> -
JS
// 封装创建XMLHttpRequest对象 function createXMLHTTPObject() { var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; var xmlhttp = false; for (var i = 0; i < XMLHttpFactories.length; i ++ ) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; } //封装异步请求函数 function request(url, callback, data) { var xmlHttp = createXMLHTTPObject(); if ( ! xmlHttp) return; var method = (data) ? "POST" : "GET"; xmlHttp.open(method, url, true); xmlHttp.setRequestHeader('User-Agent', 'XMLHTTP/1.0'); if (data) xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState != 4) return; if (xmlHttp.status != 200 && xmlHttp.status != 304) { alert('HTTP请求错误 ' + xmlHttp.status); return; } callback(xmlHttp); } if (xmlHttp.readyState == 4) return; xmlHttp.send(data); } var xhr =createXMLHTTPObject(); window.onload = function(){ var str = "test.asp?data=Hello world!"; xhr.open( "GET", str, true ); xhr.onreadystatechange = updatePage; xhr.send( null ); } function updatePage() { var info = document.getElementById( "info" ); if( xhr.readyState == 1 ) { info.innerHTML = "<img src='images/loading.gif' /> 连接中......"; } else if( xhr.readyState == 2 || xhr.readystate == 3 ) { info.innerHTML = "<img src='images/loading.gif' /> 读数据......"; } else if( xhr.readyState == 4 ) { if( xhr.status == 200 ) { info.innerHTML = "<span>" + xhr.responseText + "</span>"; } else alert( xhr.status ); } }