以下仅为本人学习使用
主要是
AJAX-XHR(创建对象)
AJAX-XHR(请求)
AJAX-XHR(响应)
AJAX-XHR(readyState)
1.创建对象
为了兼容ie5和ie6:
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
2.请求
使用XMLHttpRequest 对象的 open() 和 send() 方法
使用get时
xmlhttp.open("GET","URL?fname=Henry&lname=Ford",true);
xmlhttp.send();
使用post时,需要使用 setRequestHeader() 来添加 HTTP 头,然后在 send() 方法中规定希望发送的数据
xmlhttp.open("POST","URL",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
3.响应
获得来自服务器的响应,就需要使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性
responseText属性返回字符串形式的响应
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,就使用 responseXML 属性
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{txt=txt + x[i].childNodes[0].nodeValue + "<br>";}
document.getElementById("myDiv").innerHTML=txt;
4.readyState
readyState 属性存有 XMLHttpRequest 的状态信息
每当 readyState 改变时,就会触发 onreadystatechange 事件
XMLHttpRequest 对象的三个重要的属性
当 readyState 等于 4 且状态为 200 时,表示响应已就绪
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test").innerHTML=xmlhttp.responseText;
}
}
json字符串,JSON 比 XML 更小、更快,更易解析,我们可以使用:
JSON.parse() 方法将json字符串数据转换为 JavaScript 对象
JSON.stringify() 方法将 JavaScript 对象转换为json字符串字符串
一下是一个完整的get请求示例
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.open("GET","http://127.0.0.1/Reception/interface/getdata.php")
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState == 4 &&xmlhttp.status ==200){
//将json字符串转化为JavaScript对象
var data = JSON.parse(xmlhttp.responseText).data;
console.log(data);
console.log(data.length);
}
}