ajax问题总结 比较全

2019-09-14 07:16:14于海丽

}
else alert('发生错误nn'+xhr.status);
}
}
xhr.open("get","showbo.xml?_dc="+new Date().getTime(),true);
xhr.send(null);

解决办法就是使用microsoft.xmldom对象重新建立xml的树结构,如下

xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200||xhr.status==0){
var doc=xhr.responseXML;
if(document.all&&xhr.status==0){//为ie并且直接托进浏览器的时重构xml的树结构
doc=new ActiveXObject("microsoft.xmldom");
doc.loadXML(xhr.responseText);
doc=doc.documentElement;
}
var item=doc.getElementsByTagName("item");
alert(item.length);
}
else alert('发生错误nn'+xhr.status);
}
}

5,为post提交时需要注意的。
1)如果为post提交时,注意要设置content-type为"application/x-www-form-urlencoded",这样在动态页才可以使用request/request.form/request.querystring对象通过键获取值,否则得使用2进制数据,然后自己分析2进制数据生成字符串对象,使用正则什么的获取对应的值。
2)需要在open以后才能使用xhr.setRequestHeader方法,否则出错。
xhr.open("post","xxxx.aspx",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");//这里。。。。
6.还有一个问题忘记总结了,跨域的问题
如果请求的页面不是当前站点的,那就跨域了,最好的解决方案就是服务器端的xhr请求
可以参考下面的的解决方案
AJAX跨域问题解决办法
不久前放出的一个
使用alexa,google的api获取alexa排名和google pr,分别使用了客户端和服务器端的xhr请求
中就是使用了服务器端的xhr请求,应为请求的是Google和alexa的页面,所以跨域了,需要使用服务器端的xhr请求。
乱码问题============================================
对于ajax应用来说,乱码也是一个经常出现的问题。
1)meta声明的charset要和请求的页面返回的charset一致。最好在请求的页面中再设置下输出编码。
asp: response.charset="gb2312或者utf-8"
asp.net: response.charset="gb2312或者utf-8"
php: header("charset=gb2312或者utf-8")
2)文件物理存储编码要和meta声明的编码要一致。如meta指定为gb2312,则物理存储编码为ansi。如果为utf-8,则要存储为utf-8编码。
对于asp,如果指定编码为utf-8,记得还要设置
<%@language="vbscript" codepage="65001"%>

'防止asp使用utf-8编码时中文出现乱码
Session.CodePage=65001
Response.CharSet="utf-8"

因为asp在国内服务器默认处理编码为gb2312
对于asp.net的话,meta设置为gb2312时,最好设置web.config文件中的

<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>

,并且在输出中文前设置Response.CharSet="gb2312";
因为asp.net默认的编码为utf-8
3)发送中文到动态页面时使用escape/encodeURI/encodeURIComponent编码一下。建议使用encodeURIComponent。