欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-14 10:44:51
请求方式,分为get与post: get 最为常见的http请求,普通上网浏览页面就是get。get方式的参数请求直接跟在url后,以问号开始。(js中用window.lo...
请求方式,分为get与post:
get
最为常见的http请求,普通上网浏览页面就是get。get方式的参数请求直接跟在url后,以问号开始。(js中用window.location.search获得)。参数可以用encodeuricomponent进行编码,使用方式:
var enparam = 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请求对象。)
复制代码 代码如下:

//同步传输模式
function requestbyget(nproducttemp,ncountrytemp)
{
var xmlhttp
if (window.xmlhttprequest)
{
//isie = false;
xmlhttp = new xmlhttprequest();
}
else if (window.activexobject)
{
//isie = true;
xmlhttp = new activexobject("microsoft.xmlhttp");
}
//web page location.
var url="http://www.baidu.com/;
xmlhttp.open("get",url, false);
//xmlhttp.setrequestheader("content-type","text/html; charset=shift_jis")
xmlhttp.send(null);
var result = xmlhttp.status;
//ok
if(result==200)
{
document.getelementbyid("div_rightbarbody").innerhtml=xmlhttp.responsetext;
}
xmlhttp = null;
}

//异步传输模式
var xmlhttp
function requestbyget(nproducttemp,ncountrytemp)
{
if (window.xmlhttprequest)
{
//isie = false;
xmlhttp = new xmlhttprequest();
}
else if (window.activexobject)
{
//isie = true;
xmlhttp = new activexobject("microsoft.xmlhttp");
}
//web page location.
var url="http://www.baidu.com/";
xmlhttp.open("get",url, true);
xmlhttp.onreadystatechange = handleresponse;
//xmlhttp.setrequestheader("content-type","text/html; charset=utf-8")
xmlhttp.send(null);
}
function handleresponse()
{
if(xmlhttp.readystate == 4 && xmlhttp.status==200)
{
document.getelementbyid("div_rightbarbody").innerhtml=xmlhttp.responsetext;
xmlhttp = null;
}
}