.创建XMLHttpRequest对象
var xmhttp;
if(windows.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); }
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //ie5或 ie6 创建
.向服务器发送请求
xmlhttp.open("GET","test.txt",true);//open(method,url,async) method:请求的类型(GET或POST) url:文件
在服务器上的位置 async: ture(异步)或false(同步)
xmlhttp.send();//send(stirng) string:仅用于POST请求
.服务器响应
xmlhttp.responseText:获得字符串形式的响应数据
xmlhttp.responseXML:获得 XML 形式的响应数据
示例:
. document.getElementById("myDiv").innerHTML=xmlhttp.responseText; //获取 responseTxt
. xmlDoc=xmlhttp.responseXML; //获取 xml 数据
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;
.XMLHttpRequest对象状态( onreadystatchange=funciton(){ if(xmlhttp.readstate==4 &&
xmlhttp.status==200){ //执行代码 } } )
//当请求被发送到服务器时,我们需要执行一些基于响应的任务。
readyState:状态( 0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
)
status :状态( 200: "OK" 404: 未找到页面 )
.示例代码:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/test1.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">通过 AJAX 改变内容</button>
</body>
</html>
转载于:https://www.cnblogs.com/xmyy/articles/2017544.html