zl程序教程

您现在的位置是:首页 >  其他

当前栏目

AJAX下的请求方式以及同步异步的区别小结

同步AJAX异步 方式 区别 以及 请求 小结
2023-06-13 09:14:24 时间
请求方式,分为GET与POST:
GET
最为常见的HTTP请求,普通上网浏览页面就是GET。GET方式的参数请求直接跟在URL后,以问号开始。(JS中用window.location.search获得)。参数可以用encodeURIComponent进行编码,使用方式:
varEnParam=encodeURIComponent(param);
URL只支持大约2K的长度,即2048字符数;使用GET进行AJAX请求时候会缓存导致出现的页面不是正确的,一般方法加random参数值;ajax.send(null)。
POST
向服务器提交数据用到。
需要将form表单中的值先取出转换成字符串,用&符号连接,(同GET传参数一样);提交数据量2GB;使用ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),处理提交的字符串;ajax.send(strings),这个strings表示form中需要提交的内容,例如a=1&b=2类似这样的字符串。
同步与异步:
ajax.open方法中,第3个参数是设同步或者异步。prototype等js类库一般都默认为异步,即设为true。先说下同步的情况下,js会等待请求返回,获取status。不需要onreadystatechange事件处理函数。而异步则需要onreadystatechange事件处理,且值为4再正确处理下面的内容。
(注:文中的ajax表示XMLHTTP请求对象。)
复制代码代码如下:

//同步传输模式
functionRequestByGet(nProducttemp,nCountrytemp)
{
varxmlhttp
if(window.XMLHttpRequest)
{
//isIE=false;
xmlhttp=newXMLHttpRequest();
}
elseif(window.ActiveXObject)
{
//isIE=true;
xmlhttp=newActiveXObject("Microsoft.XMLHTTP");
}
//Webpagelocation.
varURL="http://www.baidu.com/;
xmlhttp.open("GET",URL,false);
//xmlhttp.SetRequestHeader("Content-Type","text/html;charset=Shift_JIS")
xmlhttp.send(null);
varresult=xmlhttp.status;
//OK
if(result==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
}
xmlhttp=null;
}

//异步传输模式
varxmlhttp
functionRequestByGet(nProducttemp,nCountrytemp)
{
if(window.XMLHttpRequest)
{
//isIE=false;
xmlhttp=newXMLHttpRequest();
}
elseif(window.ActiveXObject)
{
//isIE=true;
xmlhttp=newActiveXObject("Microsoft.XMLHTTP");
}
//Webpagelocation.
varURL="http://www.baidu.com/";
xmlhttp.open("GET",URL,true);
xmlhttp.onreadystatechange=handleResponse;
//xmlhttp.SetRequestHeader("Content-Type","text/html;charset=UTF-8")
xmlhttp.send(null);
}
functionhandleResponse()
{
if(xmlhttp.readyState==4&&xmlhttp.status==200)
{
document.getElementById("div_RightBarBody").innerHTML=xmlhttp.responseText;
xmlhttp=null;
}
}