一 ajax是不刷新页面从服务器端获取数据的方法
1 ajax的核心对象XMLHttpRequest对象
用法:var xhr = newXmlHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readystate ==4){
if(xhr.state==200&&xhr.state<300||xhr.state==304){
alert(xhr.responseText)
}else{
alert(error);
}
}
}
xhr.open("get","index.html",true) ; //xhr.open("请求类型如:get",“url”,"是否异步发送请求的布尔值");
xhr.setRequestHeader("myheader","myvalue");
xhr.send(null); send接收的参数为是否作为请求主体发送,如果不作为则传入null,这个参数是必须的
2跨域解决方案CORS(跨域资源共享)
IE8通过XDomainRequest对象支持CORS,其他浏览器通过XHR原生对象支持CORS
另外两种跨域通信技术:Jsonp和图像Ping
原生xhr支持:检查是否存在withCredentails属性,再检测XDomainRequest对象是否存在
function createCORSRequest(method,url){
var xhr = new XmlHttpRequest();
if("withCredentails" in xhr){
xhr.open(method,url,true);
}else if(typeof XDomainRequest != "undefined"){
var xhr = new XDomainRequest();
xhr.open(method,url);
}else{
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get","http://www.baidu.com");
if(request){
request.οnlοad= function(){
//对responseText进行处理
};
request.send();
}