AJAX提交有同步提交和异步提交两种方式。后一种方式为提交后不等服务器有响应继续执行客户端代码。可以利用异步提交显示一些界面效果,比如显示一些文字,动画等。如下代码供大家参考。
//提交客户端DataStore数据
//url--目的URL
//data--要提交的DataStore 对象或XML字符串
//action--页面的Action代码
//isAsync-true: Async mode;false: sync mode
function Execute(url,action,data,method,isAsync){
var acturl = url+"";
var hrf = document.createElement("<A href='"+url+"'>");//URL格式化
var tg = "DataStore";
document.appendChild(hrf);
acturl= hrf.href;
if(url == "#")
{
acturl = acturl.replace("#","");
var pos = acturl.indexOf("?");
if(pos>0)acturl = acturl.substr(0,pos);
}
if (acturl.indexOf("?") > 0)
acturl = acturl + "&IsExec=True&RequestAction=" + action;
else
acturl = acturl + "?IsExec=True&RequestAction=" + action;
var _data = "";
var execdata = "";
if(typeof(data) == "object")
_data = data.ToString();
else if(typeof(data) == "string")
_data = data;
if(!isBase64Encode)
{
execdata = _data.replace(//xB7/g,"%B7");//由于服务器端Request处理中点,解码时会变成问号
execdata = escape(_data).replace(//+/g,"%2B")//由于服务器端Request处理"+"解码时会变成空格
}
else
{
tg = "DataStoreBase64";
execdata = _Encode64(_data);
}
var resdata;
if(!method)method = "post";
if(method.toLowerCase() == "get"){
if(typeof(isAsync) == "undefined" || isAsync == false)
resdata = GetRequest(acturl + "&" + tg + "=" + execdata,isAsync);
else
GetRequest(acturl + "&" + tg + "=" + execdata,isAsync);
}
else if(method.toLowerCase() == "post"){
if(typeof(isAsync) == "undefined" || isAsync == false)
resdata = PostRequest(acturl,tg + "=" + execdata,isAsync);
else
PostRequest(acturl,tg + "=" + execdata,isAsync);
}
if(typeof(isAsync) == "undefined" || isAsync == false)
return new ExecResult(resdata,acturl,action,_data,method);
}
var xmlhttp = null;
function GetRequest(url,isAsync)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if(typeof(isAsync) == "undefined" || isAsync == false){
xmlhttp.Open("GET",url,false);
}
else{
xmlhttp.Open("GET",url,true);
xmlhttp.onreadystatechange = HandleStateChange;
}
xmlhttp.send();
if(typeof(isAsync) == "undefined" || isAsync == false)
return xmlhttp.responseText;
}
function PostRequest(url,data,isAsync)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if(typeof(isAsync) == "undefined" || isAsync == false)
xmlhttp.Open("POST",url,false);
else{
xmlhttp.Open("POST",url,true);
xmlhttp.onreadystatechange = HandleStateChange;
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
if(typeof(isAsync) == "undefined" || isAsync == false)
return xmlhttp.responseText;
}
//Add by Max Yu 2006-11-18
function HandleStateChange(){
if (xmlhttp.readyState == 4){
if(xmlhttp.responseText.indexOf("<DataStore") != 0)
{
var win = window.open("about:blank","_Error");
win.document.write(xmlhttp.responseText);
return;
}
if (typeof(ResDataLoaded) == "function")ResponseDataLoaded = ResDataLoaded;
if (ResponseDataLoaded != null)
ResponseDataLoaded(new DataStore(xmlhttp.responseText));
}
}